0
0
PythonHow-ToBeginner · 3 min read

How to Make POST Request in Python: Simple Guide

To make a POST request in Python, use the requests.post() function from the requests library, passing the URL and data you want to send. This sends data to a server and returns the server's response.
📐

Syntax

The basic syntax for making a POST request with the requests library is:

  • url: The web address where you send the data.
  • data: The information you want to send, usually as a dictionary.
  • requests.post(): The function that sends the POST request.
python
import requests

response = requests.post(url, data=data)
print(response.text)
💻

Example

This example shows how to send a POST request with some data and print the server's response.

python
import requests

url = 'https://httpbin.org/post'
data = {'name': 'Alice', 'age': '30'}

response = requests.post(url, data=data)
print(response.text)
Output
{ "args": {}, "data": "", "files": {}, "form": { "age": "30", "name": "Alice" }, "headers": { "Accept": "*/*", "Content-Length": "17", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org", "User-Agent": "python-requests/2.31.0", "X-Amzn-Trace-Id": "Root=1-650f4f3a-4f7a1b7a0a1b2c3d4e5f6789" }, "json": null, "origin": "0.0.0.0", "url": "https://httpbin.org/post" }
⚠️

Common Pitfalls

Common mistakes when making POST requests include:

  • Not importing the requests library.
  • Forgetting to pass data as a dictionary to the data parameter.
  • Confusing data with json parameter when sending JSON data.
  • Not checking the response status code to confirm success.

Example of wrong and right ways:

python
import requests

# Wrong: data as string instead of dictionary
url = 'https://httpbin.org/post'
data = 'name=Alice&age=30'
response = requests.post(url, data=data)  # Works but less flexible

# Right: data as dictionary
response = requests.post(url, data={'name': 'Alice', 'age': '30'})

# For JSON data, use json parameter
json_data = {'name': 'Alice', 'age': 30}
response = requests.post(url, json=json_data)

print(response.status_code)
Output
200
📊

Quick Reference

Tips for making POST requests in Python:

  • Use requests.post(url, data=your_dict) for form data.
  • Use requests.post(url, json=your_dict) to send JSON data.
  • Always check response.status_code to ensure the request succeeded.
  • Use response.text or response.json() to read the server response.

Key Takeaways

Use the requests library's post() function to send POST requests easily.
Pass data as a dictionary to the data or json parameter depending on the content type.
Always check the response status code to confirm the request was successful.
Use response.text or response.json() to access the server's reply.
Import requests before making any HTTP requests.