If your developing an application, most likely at some point you’ll encounter the need to make API calls to a server. At times this can be confusing when starting out so I’ll help you out and give you a quick rundown on how to make GET and POST calls with Alamofire.

Obviously you’ll first need to install the Alamofire pod, to do so in your Podfile file add:

pod 'Alamofire'

then in Terminal, run pod install .

After that’s done, you can import Alamofire in Xcode.

Since we’re just creating a demo, you can put the code examples in the AppDelegate .

Simple Request

In these examples, we’ll be using https://jsonplaceholder.typicode.com/. It’ll allow us to interact with an API without needing our own server etc.

Assuming it worked you should get something like this in our console:

So what did we do here?

Well we told Alamofire that we want a GET request to the URL “https://jsonplaceholder.typicode.com/posts/1" and we want the response back in JSON format.

How does Alamofire know we want a GET request?

Well by default Alamofire will do a GET request, though you can change it by adding a method parameter and by using Alamofire’s HTTPMethod enums ( .get, .post, .patch, .options, .delete ).

Here’s an example of explicitly saying we want a .get request.

Now your wondering great, we get the data but how do we grab the data for use in our applications?

As you can see we are asking for .responseJSON meaning we are getting the response back as a JSON object, we can also do .responseString .

For our example we’ll stick with JSON.

To get our JSON object, we’ll need to read into response.result.value .

As you can see your getting a warning that response.result.value is an optional.

So let’s deal with that by using guard let statement.

We have now created a dictionary called json and now lets print the body of our response.

Should get the body like so in your console:

Now that we know how to do a GET request and unwrap the JSON response into a dictionary and access the value lets see how to do a POST request.

POST Request

Here’s a simple example of a POST request:

Once this runs, you should see a output in the console of Xcode with the post title being printed out:

Wrapping up

I hope this article provided value on how to do GET and POST methods with Alamofire. As always if you have any suggestions or questions feel free to reach out.

Thanks!