Razvan.net

The place for apps & thoughts

Swift on Server: making an API Call

A small tutorial demoing how to use Swift on server with Vapor framework for making request to another REST Service.
Don’t try the classic way using URLSessions, they are not yet implemented on Linux, but luckily Vapor’s creators took care of it and made it very easy to do it.

Requirements

You must have Swift and Vapor toolkit installed. If you is not the case, check my tutorial.

Create a new project

Build the project

Create an Xcode project

If you’re on a Mac and want to use Xcode

and open it.

Otherwise just use your favourite editor to open the apigetdemo folder.

Make a new route

Open the main.swift file from the Sources/App folder, delete the posts route and create a new get route temperature

Build & run

For testing the new route:

then in a browser go to url: http://localhost:8080/temperature
You should get in return: Montpellier temperature is: <todo> °C

Prepare to make the API call

For that I’ll use a service exposed by openweathermap.org.
You must register and get you own API key (APPID) to make the calls to this API.

The GET request we’ll make will be:
http://api.openweathermap.org/data/2.5/weather?q=Montpellier,FR&units=metric&APPID=<apppid>
(replace <appid> with your own id)
and in return we’ll get a JSON like:

You can also use your own or the free one like jsonplaceholder one: https://jsonplaceholder.typicode.com/todos/4
that returns:

Make the API call

For that we’ll gonna use Vapor’s Droplet.client that makes requests to remote servers. In this exemple we’ll only use a simple GET request, but take a look at the documentation you can do more complicated requests as well.

Modify the temperature route in main.swift to look like:

In the console you can see the response and in the body the response as JSON:

Getting the temperature from the result

Looking at the JSON’s response you can see we just need the “temp” that’s in the “main” object.

So we get the temperature using:

The final result

Extra

An exemple with handling a result that contains a list of items.
For that we’ll get a list of todo items from:
https://jsonplaceholder.typicode.com/todos/

We just want to keep a list of titles from that answer:

It’s that easy, thanks to Vapor framework.