Example: POST Request - 2.3 | Chapter 12: Working with External Libraries and APIs | Python Advance
Students

Academic Programs

AI-powered learning for grades 8-12, aligned with major curricula

Professional

Professional Courses

Industry-relevant training in Business, Technology, and Design

Games

Interactive Games

Fun games to boost memory, math, typing, and English skills

Example: POST Request

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.