Skip to content

Request Bodies

Contents | Previous: Making Requests | Next: Handling Responses

After reading this chapter

You can send JSON as the usual request body and select the appropriate body form when an API requires form or multipart data.

A request body is attached to a request that sends content, such as POST, PUT, or PATCH. The HTTP client uses a typed JSON body as the default path for serializing an application DTO.

1. Send a JSON Body

A typed JSON body sends an application DTO as application/json. The response form is independent of the body format, so choose a typed response, raw response, or a body-only response as needed.

↗ 크게 보기

const player = await client.post('/players/p2').body({ nickname: 'rookie' }).submit<string>();
const room = await client.post('/rooms').body({ title: 'tutorial-room' }).fetch<string>();
// The room id returned here is used by the following room requests.
const chat = await client
  .post(`/rooms/${room}/chat`)
  .body({ playerId: 'p2', text: 'hello' })
  .submit<null>();
console.log(`json body: player ${player.status} room ${room} chat ${chat.status}`);

2. Choose Form or Multipart

A form suits an API that accepts short name and value pairs as application/x-www-form-urlencoded. Multipart is multipart/form-data for sending text fields and file fields in one request. Form fields accumulate, and multipart fields and files accumulate into one body.

Choose one body source

Mixing typed JSON, raw content, a stream, a form, or multipart in one request ends with protocolError before the request is sent.

3. Boundary for Raw and Streaming Bodies

A raw body with an arbitrary content type and a streaming upload that supplies byte chunks are separate paths from JSON, form, and multipart. Response Rules covers raw-body response handling, and Streaming covers streaming uploads.

Next Chapter

Handling Responses chooses a JSON-decoded response, a raw response, or a body-only response.