This post presents an implementation of HTTP requests in Swift without needing Alamofire, a Cocoapod, or other third-party library. Following the method in this post will allow you to make GET and POST HTTP requests to a url.
Why Not Use Alamofire and Cocoapods for HTTP requests?
Many apps do not require extensive network configuration for HTTP requests beyond what Apple-provided classes like URLSessonDataTask
allow. By implementing network requests using Apple-provided classes, a developer can:
- simplify the codebase by removing a large, third-party dependency like Alamofire
- reduce the binary size of the application
- reduce risk associated with relying on third-party dependencies
Create URL Request
The first step is to create a URLRequest
. A URLRequest
can be created with a URL
, representing the API endpoint to make a 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)
Configure HTTP Request Headers
If your HTTP request is to an API that requires authentication, you can set the necessary HTTP request headers on the URLRequest
.
// Configure request authentication
request.setValue(
"authToken",
forHTTPHeaderField: "Authorization"
)
POST HTTP Request
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 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 HTTP Request
All newly created URLSessionDataTask
objects are in a suspended state by default. To start the HTTP request, call:
task.resume()
Cancel HTTP Request
If the HTTP request needs to be cancelled after the request has started, call:
task.cancel()
FREE all Swift Loading Animations

Immediately get access to commented code for these animations when you follow Advanced Swift.
HTTP Requests in Swift
That’s it! Using URL
, URLRequest
, URLSession
, and URLSessonDataTask
allows you to make HTTP requests in Swift without external libraries and dependencies.