Skip to Content

How to pass the JSON data in the body as a POST request?

Passing JSON data in the body of a POST request is a common requirement when working with REST APIs. The JSON data contains the payload that will be used by the API to perform some action. There are a few simple steps to properly format the request in order to pass the JSON body data.

Quick Answers

Here are quick answers to common questions about passing JSON data in the body of a POST request:

  • Set the Content-Type header to application/json to indicate JSON data is being sent.
  • Convert the JSON object to a string using JSON.stringify().
  • Set the body of the request equal to the JSON string.
  • Use the fetch API or a request library like Axios to make the POST request.
  • The API will parse the JSON string back into an object and process it.
  • Always check the API documentation for specific requirements on request formatting.

Overview

When making a POST request, the client needs to provide the data to be passed to the API in the body of the request. This is often additional data that the API needs to perform some operation. For example, for a “create user” API, the JSON body would contain the new user details to be added to the system.

There are a few key steps to keep in mind when passing JSON in the body:

  1. The data must be serialized into a JSON string. JavaScript provides the JSON.stringify() method to convert a JSON object into a string.
  2. The Content-Type request header must be set to “application/json” to indicate the body contains JSON data. This tells the API how to parse the body contents.
  3. The JSON string must be set as the body of the POST request before sending it.
  4. The API will convert the JSON string back into native data structures to process.

As long as these key points are followed, the API will be able to successfully parse and consume the JSON data provided in the body. There are also helpful client libraries like fetch and Axios that make it easy to make POST requests with a JSON body.

1. Serialize the Data to JSON

The first step is to serialize the data to a JSON string. JSON stands for JavaScript Object Notation and is a lightweight format that is easy for APIs to parse.

In JavaScript, the JSON.stringify() method can be used to convert a regular JavaScript object into a JSON string that can be sent in the request body. Here is an example:

const data = {
  firstName: 'John',
  lastName: 'Doe' 
}

const json = JSON.stringify(data)

console.log(json) 

// Outputs: {"firstName":"John","lastName":"Doe"}

JSON.stringify() will take care of encoding any nested objects and arrays properly so the output is a valid JSON string.

Some points to keep in mind:

  • Keys in JSON objects must be strings. Numeric keys will get converted to strings.
  • Any JavaScript functions will get omitted from the JSON output.
  • Invalid JSON will often lead to silent failures or errors when parsing on the API end.

So in general, try to convert relatively simple JavaScript objects to JSON that consist of key-value pairs, arrays, and other primitive values that can be represented in JSON.

Escaping Characters

Certain characters need to be escaped in JSON strings with a backslash. For example:

const data = {
  message: "Hello there! How's it \"going\" today?" 
}

JSON.stringify(data)

// {"message":"Hello there! How's it \"going\" today?"}

JSON.stringify() will take care of properly escaping any characters like quotes for you.

2. Set the Content-Type Header

Once the data is converted to a JSON string, the next important step is to set the Content-Type header in the request:

Content-Type: application/json

This header indicates that the body of the request contains JSON formatted data.

When the API receives the request, it will check this header to determine how to parse the body contents.

If this header is not set properly to application/json, the API may not understand how to handle the data and return an error.

Other Common Content Types

Some other common content types you may encounter:

  • application/x-www-form-urlencoded – Standard form data encoding for submitting HTML forms
  • multipart/form-data – Used for file uploads
  • text/xml – XML formatted data

3. Set the JSON String as the Body

With the data serialized to JSON and the Content-Type header set, the last step is to simply set the stringified JSON as the body of the request.

For example, using the built-in fetch API in JavaScript:

const data = {
  firstName: 'John',
  lastName: 'Doe'
}

fetch('/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})

The JSON string created from JSON.stringify() gets set directly as the body parameter in the fetch call.

The same would apply for other request libraries like Axios:

const data = {
  firstName: 'John',  
  lastName: 'Doe'
}

axios.post('/users', JSON.stringify(data), {
  headers: {
    'Content-Type': 'application/json'
  }
})

The JSON string is passed in as the 2nd parameter to axios.post() after the URL.

Parsing the JSON

On the API side, frameworks like Express in Node.js make it easy to access the JSON body:

app.post('/users', (req, res) => {
  const userData = req.body;
  
  // userData will be the parsed JSON object
})

The JSON string is parsed automatically back into a normal JavaScript object on req.body for easy access in the route handler.

Example API Calls

Let’s look at some examples of sending JSON data in a POST request to real world APIs:

Twitter API

The Twitter API uses JSON for many of its requests and responses. For example, posting a new tweet:

POST /1.1/statuses/update.json

{
  "status":"Hello world!" 
}

The /1.1/statuses/update.json endpoint expects a JSON object with a status key for the content of the tweet. We can make this request in JavaScript like:

  
const tweet = {
  status: 'Hello world!'  
}

fetch('https://api.twitter.com/1.1/statuses/update.json', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(tweet)  
})

Stripe API

The Stripe payments API also uses JSON for many of its requests. For example, creating a charge:

POST /v1/charges  

{
  "amount": 2000,
  "currency": "usd",
  "source": "tok_visa", // obtained with Stripe.js
  "description": "My First Test Charge (created for API docs)"
}

Again we can convert the charge information to JSON and POST it:

const charge = {
  amount: 2000,
  currency: 'usd',
  source: 'tok_visa',
  description: 'My First Test Charge' 
}

fetch('https://api.stripe.com/v1/charges', {
  //...
})  

Client Libraries

There are many client libraries in various languages that make it easy to POST JSON as well as call REST APIs in general. Some popular options:

Language Libraries
JavaScript fetch, Axios, jQuery AJAX
Python requests, http.client
Ruby RestClient, HTTParty
PHP cURL, Guzzle
Java OkHttp, Retrofit

These libraries will take care of many of the implementation details like:

  • POSTing a request body
  • Setting headers like Content-Type
  • Parsing response data
  • Handling errors

So in many cases they can simplify the code needed to call an API. But understanding what is happening under the hood is still important.

Conclusion

Passing JSON in the body of a POST request is key for communicating with modern REST APIs. By serializing the data to JSON, setting the Content-Type header, and assigning the JSON string as the body, the API will be able to successfully parse and process the request data.

Leveraging libraries like fetch in JavaScript, requests in Python, and cURL in PHP can help simplify the process but understanding the core principles is still important when working with APIs.