requests Method to Send Data
Lesson 6 of 10 in Coddy's API in Python course.
Just like retrieving data with GET requests, we can send data to an API server using the .post() method.
The post() method requires a URL and typically includes headers and data as arguments. The principle is that your data will be sent to the API endpoint, and the server will process it.
The post() code structure looks like this:
import requests
response = requests.post(
"https://api.example.com/endpoint",
headers={
"Content-Type": "application/json"
},
json={
"key1": "value1",
"key2": "value2"
}
)The headers and data are passed as dictionaries with their key-value pairs.
Note:
- Headers typically include metadata about your request (like content type)
- The
jsonparameter automatically converts your Python dictionary to JSON format - Some APIs require authentication via API keys in the headers
Challenge
MediumSend a POST request to create a new user using the JSONPlaceholder API.
Instructions:
Send a POST request to: https://jsonplaceholder.typicode.com/users
Include the following header:
{"Content-Type": "application/json"}Send the following data using the json parameter:
{
"name": "James Shelby",
"email": "jamesshelbys1987@example.com",
"username": "jshelby1987"
}Save the requests.post() object to a variable called response
Print both response.status_code and response.json() to see the result
Expected output: You should receive a status code of 201 (Created) and see your user data returned with an assigned ID!
Try it yourself
import requests
response = requests.post(
# Your code here
)
print("Status Code:", response.status_code)
print("Response:", response.json())All lessons in API in Python
2API in Python
requests Library for APIrequests Method to Retrieverequests Method to Send DataManipulating requests Response3Weather Fetch API Program
API Connection to ServerGET Request to ServerDisplaying Appropriate Results