How to write your first API call


You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿


“How do I write my first API call in Swift?” 🤔

If you’re new to Swift or iOS, you’re bound to ask yourself this question at some point!

So I made this article to guide you through that process in record time ⚡️

So let’s get started!

We’re going to use an API called The Movie Database, which provides data about movies and tv shows.

And we’ll be using this API to retrieve a list of movies.

The data we’ll receive will be in the form of a JSON payload that looks like this:

So first, we need to implement a model that we will use to decode and store the data returned by the API 🤨

Luckily, it’s going to be pretty easy: we simply need to implement two structs that match the structure of the JSON payload, and make sure these structs implement the protocol Decodable:

That’s all we need to do: the compiler will take care of automatically synthesizing the rest of the deserialization code for us 👌

Next, we need to write the actual network call.

We begin by declaring a function that will contain the code of the network call:

Then, we create the URL of the API end point we want to query.

You can notice that this end point expects one argument, which is an apiKey.

To keep things simple, I’m using String interpolation to inject the apiKey in the URL:

(Please note that the apiKey I’m showing is just a placeholder, if you want to test this code you’ll need to get your own apiKey here: https://developers.themoviedb.org/3/getting-started/authentication)

Now to make the network call we’re going to use URLSession, which is Swift’s built-in tool for networking.

I’m using URLSession.shared, which is a singleton that’s already preconfigured, and I call the method .data(from: url)

Since this method is asynchronous and can throw an error, I’ll need to annotate the call site with the keywords try and await.

I’ll also need to update the signature of my function fetchMoviesFromAPI() to indicate that it can now also throw errors and call async code.

Then, I’ll need to use the result of the method .data(from: url).

This method returns a tuple that contains two elements: the data payload returned by the API and some metadata about the response.

I’m only interested in the data itself so I will ignore that second element.

Finally, we need to decode the data. For this, we’re going to use a JSONDecoder.

I’m going to create a JSONDecoder, call its method .decode(type, from: data), and pass as arguments the type of my data model and the actual data I got from the API.

Since the decoding process can also generate an error, I need to mark this call with the keyword try.

And now all that’s left to do is to simply return the array of Movie that’s been decoded from the result of the API call.

That’s it, we’ve written our first API call in Swift 🥳

If we want we can give it a try and print the array of movies to the console to make sure that our code is indeed working as expected:

That’s all for this article, I hope you’ve enjoyed this new format!

Here’s the code if you want to experiment with it!

// This is a fake apiKey, get yours at
// https://developers.themoviedb.org/3/getting-started/authentication

let apiKey = "fa9bc8815fb0fc61d5ef6b3da297a009"

func fetchMoviesFromAPI() async throws -> [Movie] {
    let url = URL(string: "https://api.themoviedb.org/3/movie/upcoming?api_key=\(apiKey)")!

    let (data, _) = try await URLSession.shared.data(from: url)

    let decoded = try JSONDecoder().decode(MoviesResponse.self, from: data)

    return decoded.results
}

Task {
    do {
        let movies = try await fetchMoviesFromAPI()

        print(movies)
    } catch {
        print(error)
    }
}
Previous
Previous

This is my first (traditional) newsletter 📮

Next
Next

Discover Generics in Swift