This post presents an implementation of GET and POST HTTP requests in Swift with URLSession. Following the method in this post will allow you to fetch data from an API using GET and POST HTTP requests.
- Create A URLRequest
- HTTP Request With Headers
- HTTP Request With URL Parameters
- POST HTTP Request With JSON Body
- Create A URLSessionDataTask
- Start URLSessionDataTask
- Cancel URLSessionDataTask
Create A URLRequest
To make an HTTP request in Swift using URLSession
first create a URLRequest
. A URLRequest
can be created with a URL
, representing the API endpoint to make a GET or POST HTTP request to.
// Create a URLRequest for an API endpoint
let url = URL(string: "https://www.myapi.com/v1/user")!
var request = URLRequest(url: url)
HTTP Request With Headers
If your HTTP request is to an API that requires authentication or other headers, you can set the necessary HTTP request headers on the URLRequest
using the setValue
method.
// Configure request authentication
request.setValue(
"authToken",
forHTTPHeaderField: "Authorization"
)
// For POST requests with a JSON body, set the Content-Type header
request.setValue(
"application/json",
forHTTPHeaderField: "Content-Type"
)
HTTP Request With URL Parameters
URLComponents
can be used to create a URL
with query parameters for an API request.
var components = URLComponents()
components.scheme = "https"
components.host = "advswift.com"
components.path = "/api/devs"
components.queryItems = [
URLQueryItem(name: "skill", value: "swift")
]
// "https://advswift.com/api/devs?skill=swift
components.string
Learn more about URLs and URL parameters in Swift:
POST HTTP Request With JSON Body
If you need to make a POST request, you can set the httpMethod
and httpBody
on the URLRequest
.
// Serialize HTTP Body data as JSON
let body = ["user_id": "12"]
let bodyData = try? JSONSerialization.data(
withJSONObject: body,
options: []
)
// Change the URLRequest to a POST request
request.httpMethod = "POST"
request.httpBody = bodyData
Create A URLSessionDataTask
To handle a request response, create a URLSessionDataTask
with a completion handler. Use the completion handler to parse the request response and handle any error that may have occurred.
// Create the HTTP request
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
if let error = error {
// Handle HTTP request error
} else if let data = data {
// Handle HTTP request response
} else {
// Handle unexpected error
}
}
Start URLSessionDataTask
All newly created URLSessionDataTask
objects are in a suspended state by default. To start the HTTP request, call:
task.resume()
Cancel URLSessionDataTask
If the HTTP request needs to be cancelled after the request has started, call:
task.cancel()
HTTP Requests in Swift
That’s it! Using URL
, URLRequest
, URLSession
, and URLSessonDataTask
allows you to make HTTP requests and fetch data from APIs in Swift without external libraries and dependencies.