2.3 - Example: POST Request
Enroll to start learning
Youβve not yet enrolled in this course. Please enroll for free to listen to audio lessons, classroom podcasts and take practice test.
201
print(response.json())
π Long Summary
πΈ What is a POST Request?
A POST request sends data to the server for creating/updating resources.
Data is sent in the body of the request, often in JSON or form-encoded format.
Not idempotent β sending the same request twice may result in two resources.
πΈ Syntax and Parameters
python
requests.post(url, data=None, json=None, headers=None, timeout=None)
data: Dictionary for form-encoded data (application/x-www-form-urlencoded)
json: Dictionary for JSON payload (automatically sets correct Content-Type)
headers: Custom headers
timeout: Request timeout in seconds
πΈ Example with JSON Payload
python
import requests
new_post = {"title": "New Post", "body": "Example content", "userId": 2}
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=new_post)
print(response.status_code) # Should be 201
print(response.json()) # See created object
πΈ Error Handling
python
try:
response = requests.post(url, json=data, timeout=10)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print("Request failed:", e)
When should you use a POST request instead of GET?
Answer: When you want to send data to the server, such as creating a resource.
Hint: It usually modifies server state.
How do you send JSON data in a POST request using requests?
Answer: Use the json keyword argument.
Hint: Avoid data=json.dumps(...) unless manually setting headers.
What status code indicates successful creation from a POST request?
Answer: 201 Created.
Hint: Different from 200 OK.
Whatβs the difference between data and json in a POST request?
Answer: data sends form-encoded data, json sends a JSON body.
Hint: json automatically sets content type headers.