HTTP Request
We can send and receive data from a server using the Swift native component URLSession
. In this article we'll explore how to do a GET and a POST request with parameters.
For the following examples we will use a test url that returns an array of products. https://educaswift.com/public/products.json
Create and send our Request
The steps to create and send a request to the server will be:
- Create a
URL
. - Create a
URLRequest
where we can indicate the method (GET , POST, PATCH, PUT or DELETE). - Call
data(for: URLRequest)
using the standard URLSession. - Decode the response.
- Handle error in case of any.
func downloadProducts() async {
guard let url = URL(string: "https://educaswift.com/public/products.json") else {
return
}
do {
let request = try URLRequest(url: url, method: .get)
let (data, _) = try await URLSession.shared.data(for: request)
let products = try JSONDecoder().decode([Product].self, from: data)
self.products = products
}
catch let error {
print("Error downloading products: \(error.localizedDescription)")
}
}
In order to decode our Product
list we created the following model.
struct Product: Decodable, Identifiable {
var id: Int
var title: String
var description: String
var price: String
var thumbnail: String
}
As our model is Identifiable
, we can show the result in a List
easily.
@State var products: [Product] = []
var body: some View {
List(products) { product in
Text(product.title)
}
.onAppear {
Task {
await downloadProducts()
}
}
}
Request parameters
We can add parameters to our request, this will be done differently for GET and POST requests.
Get parameters
Even if you can put your parameters directly in your url string, it's recomended to use URLComponents
for safety reasons. As you can see in the example, you will be able to check if the url is correct before continuing.
var urlComponents = URLComponents(string: "https://educaswift.com/public/products.json")
urlComponents?.queryItems?.append(URLQueryItem(name: "page", value: "1"))
guard let url = urlComponents?.url else {
return
}
...
Post parameters
On the other side, to add parameter to a POST request we need add a body to it. The best way to do this is using Encodable
protocol. We can have a model that we'll use to handle the parameters we need and then we will encode it to Data
to set our request body:
struct MyRequestParameters: Encodable {
let page: Int
}
guard let url = URL(string: "https://educaswift.com/public/products.json") else {
return
}
do {
var request = try URLRequest(url: url, method: .post)
var parameters = MyRequestParameters(page: 1)
request.httpBody = try? JSONEncoder().encode(parameters)
...
This is a very brief example, but obviously is recommended to handle the errors from trying to encode the data.
Request headers
Set any header you need in your request with the setValue(:forHTTPHeaderField)
.
do {
var request = try URLRequest(url: url, method: .post)
request.setValue("application/json", forHTTPHeaderField: "accept")
...
Be the first to comment