0
0
Rest APIprogramming~5 mins

POST for creating resources in Rest API

Choose your learning style9 modes available
Introduction

POST is used to send data to a server to create a new item or resource. It helps add new things like users, posts, or products.

When you want to add a new user to a website.
When you need to upload a new photo or file.
When creating a new blog post or article.
When submitting a form with information to save.
When adding a new product to an online store.
Syntax
Rest API
POST /resource HTTP/1.1
Host: example.com
Content-Type: application/json

{
  "key": "value"
}
The POST request sends data in the body, usually in JSON format.
The URL points to the collection where the new resource will be added.
Examples
This creates a new user with name and email.
Rest API
POST /users HTTP/1.1
Host: example.com
Content-Type: application/json

{
  "name": "Alice",
  "email": "alice@example.com"
}
This adds a new blog post with a title and content.
Rest API
POST /posts HTTP/1.1
Host: example.com
Content-Type: application/json

{
  "title": "My First Post",
  "content": "Hello world!"
}
Sample Program

This Python program sends a POST request to create a new post with title, body, and userId. It prints the status code and the response from the server.

Rest API
import requests

url = 'https://jsonplaceholder.typicode.com/posts'
data = {
    'title': 'foo',
    'body': 'bar',
    'userId': 1
}

response = requests.post(url, json=data)
print('Status code:', response.status_code)
print('Response body:', response.json())
OutputSuccess
Important Notes

POST requests usually return status code 201 when a resource is created successfully.

The server response often includes the new resource's ID or details.

Always set the Content-Type header to tell the server the data format.

Summary

POST is used to create new resources by sending data to the server.

Data is sent in the request body, often as JSON.

Successful creation usually returns status 201 and the new resource info.