How to make POST, GET, PUT and DELETE requests with Alamofire using Swift

Last updated on: May 27, 2023

In this tutorial, I’m going to show you how to use all HTTP methods (GET, POST, PUT, DELETE) using the 3rd party library Alamofire on iOS.

Adding the library

In this example, we are going to add the Alamofire library to our project using Cocaopods.

Open your Podfile with your favorite text editor (e.g Visual Studio Code) and add pod 'Alamofire'

Then, run pod update in the terminal

Adding data using the POST method

If you want to send data to the server, as we do in this example by uploading an employee’s data(name, salary, and age) to the database, then use the HTTP method POST.

In this example, the data we have to upload needs to be in the following JSON format:

{
  "age" : "23",
  "name" : "Jack",
  "salary" : "3540"
}Code language: Swift (swift)

In Alamofire, you don’t need to define application/json as Content-Type in the HTTP Header, as you do in URLSession

func postMethod() {
    let params: Parameters = [
        "name": "Jack",
        "salary": "3540",
        "age": "23"
    ]
    
    AF.request("http://dummy.restapiexample.com/api/v1/create", method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil).validate(statusCode: 200 ..< 299).responseData { response in
        switch response.result {
            case .success(let data):
                do {
                    guard let jsonObject = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
                        print("Error: Cannot convert data to JSON object")
                        return
                    }
                    guard let prettyJsonData = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted) else {
                        print("Error: Cannot convert JSON object to Pretty JSON data")
                        return
                    }
                    guard let prettyPrintedJson = String(data: prettyJsonData, encoding: .utf8) else {
                        print("Error: Could print JSON in String")
                        return
                    }
            
                    print(prettyPrintedJson)
                } catch {
                    print("Error: Trying to convert JSON data to string")
                    return
                }
            case .failure(let error):
                print(error)
        }
    }
}Code language: Swift (swift)

Retrieving data using the GET method

Use the HTTP method GET to retrieve information from REST API, like user info in a social media API (e.g. Facebook Graph API)

func getMethod() {
    AF.request("http://dummy.restapiexample.com/api/v1/employees", parameters: nil, headers: nil).validate(statusCode: 200 ..< 299).responseData { response in
        switch response.result {
            case .success(let data):
                do {
                    guard let jsonObject = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
                        print("Error: Cannot convert data to JSON object")
                        return
                    }
                    guard let prettyJsonData = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted) else {
                        print("Error: Cannot convert JSON object to Pretty JSON data")
                        return
                    }
                    guard let prettyPrintedJson = String(data: prettyJsonData, encoding: .utf8) else {
                        print("Error: Could print JSON in String")
                        return
                    }
                    
                    print(prettyPrintedJson)
                } catch {
                    print("Error: Trying to convert JSON data to string")
                    return
                }
            case .failure(let error):
                print(error)
        }
    }
}Code language: Swift (swift)

Updating data using the PUT method

If you have the data already, and you want to update them, you can use the HTTP method PUT. Sometimes you can do the same with the POST method.

This method will replace the previous data with the new ones.

func putMethod() {
    let params: Parameters = [
        "name": "Nicole",
        "job": "iOS Developer"
    ]
    
    AF.request("https://reqres.in/api/users/2", method: .put, parameters: params, headers: nil).validate(statusCode: 200 ..< 299).responseData { response in
        switch response.result {
            case .success(let data):
                do {
                    guard let jsonObject = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
                        print("Error: Cannot convert data to JSON object")
                        return
                    }
                    guard let prettyJsonData = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted) else {
                        print("Error: Cannot convert JSON object to Pretty JSON data")
                        return
                    }
                    guard let prettyPrintedJson = String(data: prettyJsonData, encoding: .utf8) else {
                        print("Error: Could print JSON in String")
                        return
                    }
                    
                    print(prettyPrintedJson)
                } catch {
                    print("Error: Trying to convert JSON data to string")
                    return
                }
            case .failure(let error):
                print(error)
        }
    }
}Code language: Swift (swift)

Removing data using the DELETE method

Remove data from your REST API server using the HTTP method DELETE.

func deleteMethod() {
    AF.request("https://my-json-server.typicode.com/typicode/demo/posts/1", method: .delete, parameters: nil, headers: nil).validate(statusCode: 200 ..< 299).responseData { response in
        switch response.result {
            case .success(let data):
                do {
                    guard let jsonObject = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
                        print("Error: Cannot convert data to JSON object")
                        return
                    }
                    guard let prettyJsonData = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted) else {
                        print("Error: Cannot convert JSON object to Pretty JSON data")
                        return
                    }
                    guard let prettyPrintedJson = String(data: prettyJsonData, encoding: .utf8) else {
                        print("Error: Could print JSON in String")
                        return
                    }

                    print(prettyPrintedJson)
                } catch {
                    print("Error: Trying to convert JSON data to string")
                    return
                }
            case .failure(let error):
                print(error)
        }
    }
}Code language: Swift (swift)

In this example, the URL I’m using for the DELETE method doesn’t return any response after deleting the item. That’s why the results are empty.

You can find the final project here

If you have any questionsplease feel free to leave a comment below

Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments