Skip to Content

What is POST in API?

APIs (Application Programming Interfaces) allow different software systems to communicate with each other. APIs work by exposing endpoints that can be requested to retrieve or send data. There are several HTTP request methods that are commonly used with APIs, including GET, POST, PUT, PATCH, and DELETE.

The POST method is one of the most widely used HTTP methods for APIs. In this article, we’ll take a deep dive into understanding POST requests, how they work, and their common use cases when building and consuming APIs.

What is a POST Request?

A POST request is an HTTP method that is used to send data to a server. The data sent to the server is stored in the request body of the HTTP request.

Some key characteristics of POST requests:

  • POST requests are used to send data to the server to create or update a resource.
  • Data is sent in the body of the request, not the URL.
  • POST requests are used when submitting web forms.
  • Can send arbitrary data of any form in the body.

In contrast to GET requests, POST requests do not cache, remain in browser history, can be bookmarked, or directly linked. This makes them suitable for sending data that should not be exposed in URLs, like passwords.

How Do POST Requests Work?

When a POST request is made to an API endpoint, the following happens:

  1. Client makes HTTP POST request to endpoint URL.
  2. Request contains headers with metadata like authentication tokens, content type.
  3. Body contains data to send to server, like JSON or XML.
  4. Server processes request and creates/updates resources based on data sent.
  5. Server returns response, confirming resource creation or errors.

The overall flow looks like:

Client Server
POST /api/users
{ “name”: “John Doe” }
201 Created
{ “id”: 123 }

The client makes a POST request to the /api/users endpoint containing the user data to create in the body. The server processes this, creates a new user resource, and returns a 201 response with the new resource representation confirming creation.

Common Uses of POST Requests

Here are some of the most common uses and examples of POST requests:

Submitting Web Forms

POST is used when submitting HTML web forms. The form data gets sent in the body of the POST request when the form is submitted.

<form action="/contact" method="post">
  <input type="text" name="name">   
  <input type="email" name="email">
  <input type="submit" value="Submit">
</form> 

Sending User Registration/Signup Data

POST is commonly used when creating new user accounts and sending user registration data to APIs.

POST /api/users

{
  "name": "John",
  "email": "[email protected]",
  "password": "secret" 
}

Making Purchases/Transactions

For ecommerce or financial transactions, POST requests containing order or payment details are made to API endpoints to process purchases.

POST /api/payments

{
  "amount": 99.99,
  "creditCard": "4111111111111111",
  "expDate": "2025-12" 
} 

Uploading Files

POST can be used to upload files to API endpoints that handle them. The file data is sent in the request body.

POST /api/images/upload

<binary file data>

Adding/Updating Resources

To add new resources or update existing resources in an API, POST requests are made with data to update or create the resource.

POST /api/products

{
  "name": "New Product",
  "description": "This is a new product."  
}

POST Request Examples

Here are some examples of making POST requests using curl, jQuery, Python, and Node.js:

cURL

curl -X POST https://api.example.com/users \
  -H 'Content-Type: application/json' \
  -d '{ "name": "John Doe" }'

jQuery AJAX

$.ajax({
  method: "POST",
  url: "/api/users",
  data: { name: "John" }
});

Python Requests

import requests 

url = 'https://api.example.com/users'
data = {'name': 'John'}

response = requests.post(url, json=data)

Node.js

const https = require('https');

const data = JSON.stringify({
  name: 'John'  
});

const options = {
  hostname: 'api.example.com',
  path: '/users',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
};

const req = https.request(options, res => {
  console.log(`statusCode: ${res.statusCode}`);
});

req.write(data);
req.end();

POST Request Headers

There are some important request headers to consider when making POST requests:

Header Description
Content-Type Tells the server format of data sent – e.g. application/json, multipart/form-data
Accept Format desired for response – e.g. application/json
Authorization Contains authentication info like API tokens
Content-Length Length of request body

Content-Type tells the server how to parse the POST data, while Accept informs it how to format the response. Authorization provides API credentials for authenticated requests.

POST vs GET

GET and POST are the most widely used HTTP methods. Here is a comparison:

GET POST
Used for Retrieving resources Creating/updating resources
Sent via URL parameters Request body
Caching Can be cached Not cached
Bookmarked Can be bookmarked Cannot be bookmarked
Data Type Only text Any type of data
Security Low, exposed in URL Higher, not exposed in URL
Idempotent Yes No

In summary:

  • GET is used to retrieve data without changing server state.
  • POST is used to send data to create/update resources, changing server state.
  • GET parameters are not secure, POST data is sent in request body.
  • GET can be cached, POST cannot be cached.

Conclusion

POST requests are a fundamental method used in APIs and web development to create and update resources on the server. Understanding how to properly use POST requests will help you better leverage and build RESTful APIs.

Key points to remember:

  • POST sends data in request body instead of URL.
  • Used to create/update resources and submit web forms.
  • Various data formats like JSON can be sent.
  • Headers like Content-Type help server parse data.
  • More secure than GET since data not exposed in URL.
  • Enabled rich CRUD functionality unlike just reading data with GET.

With this comprehensive overview of POST, you should feel confident using it for creating robust APIs and web applications.