POST requests with a JSON body

Networking Junior Swift 5.5+ iOS 15+ Reviewed By Alok Singh

Fill the blank

Fill the blank to send newUser (an Encodable struct) as JSON.

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = ____
let (data, response) = try await URLSession.shared.data(for: request)
Options
Hint 1 of 1

Which API works with Encodable?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A try JSONEncoder().encode(newUser)

Correct. It turns the Encodable value into JSON Data.

Why not the others?
  • B newUser as Data. A struct can't be cast to Data.
  • C try JSONSerialization.data(withJSONObject: newUser). JSONSerialization only accepts Foundation types, so a custom struct crashes.
  • D String(describing: newUser).data(using: .utf8). That is a debug description, not JSON.

30-second answer

Create a URLRequest, set httpMethod = "POST" and the Content-Type: application/json header, encode your Encodable value with JSONEncoder into httpBody, and send it with URLSession.shared.data(for:). Check the status code, and decode the response if the server returns one.

Practise saying it · 30 s. No recording, just a timer

Explain how you send a JSON POST.

Say your answer out loud, then check which of these points you covered:

  • URLRequest with method and header
  • JSONEncoder body
  • Check status

Deep dive

Set Accept: application/json if the server negotiates content.

Use an idempotency key header for retries of non-idempotent requests.

Configure encoder strategies (dates, keys) once and reuse them.

For large bodies use upload(for:from:) or a file upload.

Common mistakes

  • Forgetting the Content-Type header.
  • Using JSONSerialization with custom structs.

Senior take & follow-ups

Seniors mention idempotency and shared encoder configuration.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why add an idempotency key?

    Show hint

    So a retried POST doesn't create duplicates.

  2. How do you send dates?

    Show hint

    Set dateEncodingStrategy, for example .iso8601.

Suggest a fix if something here is wrong or out of date.