How to send a POST request with BODY in swift
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In Swift, sending a POST request with a body means creating a URLRequest, setting the HTTP method to POST, adding the body data, and then sending it with URLSession. The important details are the body encoding and the matching Content-Type header.
A Simple JSON POST Request
A common case is sending JSON to an API.
This is the modern async and await form. The body is encoded as JSON, assigned to httpBody, and sent as part of the request.
Why Headers Matter
The server needs to know how to interpret the request body. That is why Content-Type matters.
Typical values are:
- '
application/jsonfor JSON APIs' - '
application/x-www-form-urlencodedfor form-style payloads' - '
multipart/form-datafor file uploads'
If the header does not match the body format, the server may reject the request or parse it incorrectly.
Form-Encoded Body Example
Not every API expects JSON. Some older endpoints still want form data.
The transport mechanism is the same. Only the encoding and header change.
If You Are Not Using Async and Await
Older Swift code often uses a completion handler instead.
That still works. Async and await is just easier to read when your deployment target allows it.
Validate the Response Too
A POST request is not complete just because the network call returned data. You should also inspect:
- the status code
- any server error payload
- timeouts or transport errors
That is especially important for APIs that return JSON error bodies with useful diagnostics.
It is also common to decode the success body into a Swift type instead of printing raw text. Once the response format is known, JSONDecoder should usually be the next step after validating the HTTP status code.
That keeps the networking layer type-safe and easier to evolve.
It also simplifies testing.
Common Pitfalls
The most common mistake is forgetting to set the httpMethod to POST, which leaves the request as a GET.
Another mistake is sending JSON in httpBody but not setting the Content-Type header to application/json.
A third pitfall is building the request body as a plain string when JSON encoding would be safer and less error-prone.
Summary
- Build a
URLRequest, sethttpMethodtoPOST, and assign data tohttpBody. - Match the body encoding to the correct
Content-Typeheader. - Use
JSONEncoderfor JSON payloads whenever possible. - Send the request with
URLSession, ideally using async and await in modern Swift. - Check the HTTP response, not just whether the network call returned data.

