Python > Working with External Resources > APIs (Application Programming Interfaces) > RESTful APIs
Sending Data to a RESTful API using `requests` (POST Request)
This snippet demonstrates how to send data to a RESTful API using a POST request with the `requests` library. POST requests are commonly used to create new resources on the server.
Prerequisites
Make sure you have the `requests` library installed: `pip install requests`
Importing the `requests` library
Import the `requests` library to work with HTTP requests.
import requests
Making a POST Request
This function `create_resource` takes a URL and data (a dictionary) as input. It sends a POST request to the specified URL with the data in JSON format. The `json=data` argument tells `requests` to serialize the data as JSON and set the `Content-Type` header to `application/json`. It handles potential errors and returns the JSON response from the API.
def create_resource(url, data):
try:
response = requests.post(url, json=data)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error creating resource: {e}")
return None
Example Usage
This section demonstrates how to use the `create_resource` function. We define an `api_url` and the data for a new post. We call `create_resource` to send the data to the API. If the request is successful, we print the response from the API, which typically includes the ID of the newly created resource.
if __name__ == '__main__':
api_url = 'https://jsonplaceholder.typicode.com/posts'
new_post = {
'title': 'My New Post',
'body': 'This is the content of my new post.',
'userId': 1
}
created_post = create_resource(api_url, new_post)
if created_post:
print("Resource created successfully:")
print(created_post)
Concepts Behind the Snippet
This snippet illustrates how to send data to an API to create a new resource. The POST method is used to send data to the server, which then processes the data and creates a new resource. The JSON format is used to encode the data being sent to the server. The `Content-Type` header is set to `application/json` to inform the server that the data is in JSON format.
Real-Life Use Case
Consider building a blog application. When a user submits a new blog post, you would use this type of code to send the post data (title, content, author, etc.) to your server's API. The server would then save the new post to the database.
Best Practices
Interview Tip
Be prepared to discuss the differences between GET and POST requests, the purpose of the `Content-Type` header, and how to handle different types of responses from the API (e.g., success, error, validation failure).
When to Use Them
Use POST requests when you need to create new resources on the server, such as creating a new user account, submitting a form, or uploading a file.
Alternatives
Again `aiohttp` can be used for asynchronous requests.
Pros
Cons
FAQ
-
What is the difference between GET and POST requests?
GET requests are used to retrieve data from the server. POST requests are used to send data to the server to create or update resources. GET requests typically do not have a request body, while POST requests do. -
What does `json=data` do in the `requests.post()` function?
This argument tells the `requests` library to serialize the `data` dictionary as JSON and include it in the body of the POST request. It also sets the `Content-Type` header to `application/json`. -
How can I send data in a different format (e.g., form data)?
You can use the `data=` parameter instead of `json=`. For example: `response = requests.post(url, data=data)`. The `data` parameter accepts a dictionary or a list of tuples representing form data.