Welcome to this lesson on sending data with POST requests using Swift. As you continue your exploration of interacting with RESTful APIs, you'll learn how to send data to a server using the POST
method. POST
requests are essential when creating new resources or submitting data, such as filling out a web form or adding a new entry to a database. Unlike GET
requests, which you have already encountered, POST
requests transmit data to an API.
Understanding these differences is crucial as you expand your skill set in HTTP methods. Let's dive deeper into utilizing POST
requests to comprehend how they stand apart from GET
requests in Swift.
Before diving into POST
requests, let's briefly compare them to GET
requests:
-
GET Requests:
- Purpose: Retrieve data from a server.
- Data Location: Data is sent in the URL as path or query parameters.
- Success Status: Expect a
200
status code for successful data retrieval.
-
POST Requests:
- Purpose: Send data to a server to create or update a resource, such as submitting a form or adding a new item to a database.
- Data Location: Data is sent in the request body.
- Success Status: Expect a
201
status code for successful resource creation.
Another important difference between GET and POST is security and data visibility. Since GET requests append data to the URL as query parameters, this data is stored in browser history, logged in servers, and visible in network tools. This makes GET unsuitable for sensitive data, such as passwords or personal information. In contrast, POST requests send data in the body, making them less exposed.
These differences clarify when to use each method. POST
requests, in particular, require careful handling of the request body.
For POST
requests, the request body is crucial as it holds the data you want to send to the server. This data is usually structured in formats like JSON, which is common due to its readability and compatibility.
Here is an example of a Swift structure for a JSON request body:
Swift1struct Todo: Codable {
2 let title: String
3 let description: String
4 let done: Bool
5}
6
7let newTodo = Todo(title: "Learn Swift URLSession", description: "Complete a course on Swift API calls.", done: false)
This represents a new todo item, including a title, completion status, and description. Noticeably, we are not sending an id
, as this is typically managed by the server upon resource creation.
In Swift, we use URLSession
to perform network operations, including POST
requests. Ensure you have the base URL for your API endpoint, which in our scenario is http://localhost:8000
. Here’s a quick reminder of what you need to get started:
Swift1let baseURL = "http://localhost:8000"
This sets up the foundation for us to explore POST
requests further.
Let's walk through an example of how to craft a POST
request to add a new todo item to our API.
First, we will need to prepare the data we wish to send. We will be adding a new todo item with a specific title, a completion status, and a description:
Swift1let newTodo = Todo(title: "Learn Swift URLSession", description: "Complete a course on Swift API calls.", done: false)
2
3guard let url = URL(string: "\(baseURL)/todos") else { return }
4
5var request = URLRequest(url: url)
6request.httpMethod = "POST"
7request.setValue("application/json", forHTTPHeaderField: "Content-Type")
8
9let encoder = JSONEncoder()
10do {
11 request.httpBody = try encoder.encode(newTodo)
12} catch {
13 print("Failed to encode new todo: \(error)")
14 return
15}
In Swift, you use URLSession
to send the request:
Swift1let task = URLSession.shared.dataTask(with: request) { data, response, error in
2 guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 201,
3 let data = data else {
4 print("Failed to add a new todo")
5 return
6 }
7
8 do {
9 let createdTodo = try JSONDecoder().decode(Todo.self, from: data)
10 print("New todo added successfully!")
11 print("Created Todo: \(createdTodo)")
12 } catch {
13 print("Failed to decode response: \(error)")
14 }
15}
16
17task.resume()
Interpreting the response from a POST
request is an integral part of the process. After sending the request, the server provides a response indicating whether the operation was successful. A 201
status code signifies successful resource creation. Typically, POST
requests return the newly created resource in the response body.
This code evaluates the server's response, confirming success with a 201
status code, allowing you to print and use the details of the new todo. Otherwise, the code handles potential errors by outputting relevant error information.
In this lesson, you have learned how to send data to an API using POST
requests in Swift. We explored how POST
differs from GET
in its function of creating new resources. With URLSession
in Swift, you are equipped to craft and send POST
requests, handle responses, and manage errors to ensure robust API interactions.
As you proceed to the practice exercises, you will have the opportunity to apply everything you have learned here. Practice creating POST
requests to reinforce your understanding and discover firsthand the nuances of sending data to an API. Keep up the excellent work, as each lesson brings you closer to mastering API interactions with Swift!
