POST Requests in REST API
POST is an HTTP method commonly used to submit data to a server and create a new resource through a REST API.
For example, when a user registers on a website, submits a form, or adds a new product, the client can send a POST request containing the required data. The server validates the data, processes it, and returns an appropriate response.
In Node.js and Express.js, we can create POST endpoints using
app.post(). JSON request bodies can be parsed using
the built-in express.json() middleware.
1. What Is a POST Request?
A POST request submits data to a server for processing. It is commonly used to create a new resource in a REST API.
Examples include:
- Creating a new user account.
- Adding a new product to a product collection.
- Submitting an order.
- Sending form data to a server.
POST /api/products
Content-Type: application/json
{
"name": "Laptop",
"price": 55000
}
In this request, the client sends a product name and price in the request body. The server can validate the data and create a product if the information is valid.
2. How a POST Request Works
The client sends data to a POST endpoint. Express parses the request body, the route handler validates and processes the data, and the server returns a response.
Step 1: Client
Submits product information
Step 2: POST Request
POST /api/products
Step 3: JSON Middleware
Parses the JSON request body
Step 4: Route Handler
Validates and processes the submitted data
Step 5: API Response
Returns the created resource and status code
The middleware must be registered before the route that uses
the parsed request body. Otherwise, req.body may
not contain the expected JSON data.
3. Creating a Simple POST API
Let us create a POST endpoint that accepts a product name and price and adds the product to an in-memory array.
Step 1: Create app.js
const express = require('express');
const app = express();
// Parse incoming JSON request bodies
app.use(express.json());
const products = [];
let nextId = 1;
// POST endpoint
app.post('/api/products', (req, res) => {
const { name, price } = req.body;
if (
typeof name !== 'string' ||
name.trim() === '' ||
typeof price !== 'number' ||
!Number.isFinite(price) ||
price <= 0
) {
return res.status(400).json({
message: 'Valid name and positive price are required'
});
}
const product = {
id: nextId++,
name: name.trim(),
price
};
products.push(product);
res.status(201).json({
message: 'Product created successfully',
product
});
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Step 2: Install Express.js
npm init -y
npm install express
Step 3: Run the application
node app.js
Expected terminal output:
Server running on port 3000
The array stores products only while the server process is running. Restarting the application clears this in-memory data.
4. Sending a POST Request Using Postman
Postman is a tool used to send HTTP requests and inspect API responses. We can use it to test a POST endpoint.
Step 1: Select the HTTP method
Open Postman and select POST from the HTTP method dropdown.
Step 2: Enter the endpoint URL
http://localhost:3000/api/products
Step 3: Select the request body
- Open the Body tab.
- Select raw.
- Choose JSON as the format.
- Enter the following JSON data.
{
"name": "Laptop",
"price": 55000
}
Step 4: Click Send
If the server receives valid data, it creates a product and returns a response with HTTP status code 201.
Expected response:
{
"message": "Product created successfully",
"product": {
"id": 1,
"name": "Laptop",
"price": 55000
}
}
application/json. Postman's raw JSON body option
normally configures this header automatically.
5. Understanding req.body
In Express.js, req.body contains data parsed from
the incoming request body when the appropriate body-parsing
middleware is registered.
Consider this request body:
{
"name": "Keyboard",
"price": 1500
}
This code reads the submitted properties:
const { name, price } = req.body;
console.log(name);
console.log(price);
Example terminal output:
Keyboard
1500
The destructuring syntax extracts the name and
price properties from the request body.
6. Diagram 2: Request Body to API Response
This diagram shows how the submitted JSON data is processed before the server returns a response.
JSON Request Body
Name and price are submitted
express.json()
Parses the JSON body into req.body
Validation
Checks name and price
Valid Data
Invalid Data
The application should create the resource only after the submitted data passes validation. If the data is invalid, it should return a suitable error response.
7. POST Request With Invalid Data
A REST API should not blindly accept all submitted values. Let us send invalid product data to our example endpoint.
Example request body:
{
"name": "",
"price": -100
}
The example API checks whether the name is a non-empty string and whether the price is a positive finite number. This request fails those checks.
Expected response:
{
"message": "Valid name and positive price are required"
}
The API returns HTTP 400 Bad Request and does not add a product for this invalid request.
8. Common HTTP Status Codes for POST Requests
| Status Code | Meaning | Typical Use |
|---|---|---|
| 201 Created | A new resource was created successfully. | Product creation succeeded. |
| 200 OK | The request succeeded. | A POST operation completed without using 201. |
| 400 Bad Request | The request data is invalid. | A required field is missing or a value is invalid. |
| 401 Unauthorized | Authentication credentials are missing or invalid. | The endpoint requires authentication. |
| 500 Internal Server Error | An unexpected server-side error occurred. | An internal operation fails unexpectedly. |
9. Best Practices for POST APIs
- Use POST when submitting data for processing or resource creation.
- Register
express.json()before routes that read JSON request bodies. - Validate incoming data on the server.
- Return HTTP 201 when a resource is successfully created.
- Do not trust values received from the client.
- Use a database when created resources must persist.
- Do not expose internal errors or sensitive information in responses.
- Use authentication and authorization where the operation requires them.
Important Points to Remember
- POST is commonly used to submit data and create resources.
- Use
app.post()to define a POST endpoint in Express.js. - Use
express.json()to parse JSON request bodies. - Access parsed body data through
req.body. - Validate incoming data before creating a resource.
- Use HTTP 201 when a resource is successfully created.
- Use HTTP 400 when the submitted data is invalid.
- In-memory data is temporary and is not a substitute for database storage.
Summary
POST is an HTTP method commonly used to submit data to a
REST API and create resources. Express.js provides
app.post() to define POST endpoints, while
express.json() parses JSON request bodies.
By validating request data, returning suitable status codes, and storing resources appropriately, we can build POST endpoints that behave reliably and securely.