How to send data to a REST API with POST in Python
Sending data to a REST API with POST in Python is one of the most common tasks in system integration. While a GET request is used to read information, the POST method is used to send new data — creating a customer, submitting a form or registering an order. The good news is that, with the requests library, it only takes a few lines to do it cleanly and readably.
Prerequisites
- Python 3.8 or higher installed on your computer.
- The
requestslibrary (we install it in Step 1). - An endpoint that accepts POST. To learn, we will use the public testing service
https://httpbin.org/post, which returns exactly what we send. - Familiarity with Python dictionaries, since they are the basis of the data we will send.
Step 1: Install and import the requests library
The requests library does not come bundled with Python, so we install it with pip. In the terminal, run the following command:
pip install requests
Then, at the top of your script, import it so you can use it:
import requests
Step 2: Prepare the data you are going to send
Almost all modern APIs exchange information in JSON format. In Python, the most practical approach is to start with a regular dictionary containing the fields we want to send. Let's imagine we are creating a new customer:
novo_cliente = {
"nome": "Ana Silva",
"email": "ana.silva@exemplo.pt",
"plano": "premium"
}
Note that you don't need to convert this dictionary to JSON text by hand. As you'll see in the next step, the requests library does that conversion for you. You can include numbers, text and even lists or dictionaries inside it — the structure is converted to JSON as it is.
Step 3: Send the data with requests.post
To send the dictionary as JSON, we use requests.post and pass the data in the json= parameter. This parameter handles two things at once: it converts the dictionary to JSON and sets the Content-Type: application/json header automatically.
url = "https://httpbin.org/post"
resposta = requests.post(url, json=novo_cliente, timeout=10)
Always use json= when you want to send JSON, not data=. With data=, the fields would be sent as a form, which is a different format that most data APIs do not expect.
Tip: the timeout=10 parameter prevents your program from hanging forever if the API does not respond. Always include it in your requests.
Step 4: Read the response and check the status code
After sending the request, the API replies with a status code. The codes 200 (OK) and 201 (Created) mean everything went well. We can read that code and the response body like this:
print("Código:", resposta.status_code)
dados = resposta.json()
print(dados)
The resposta.json() method converts the JSON response into a Python dictionary, ready to be used in the rest of your program.
Step 5: Handle common errors
In production, things don't always go smoothly: the API may reject the data or the network may fail. To avoid letting an error pass silently, we use raise_for_status(), which raises an exception when the code is an error (4xx or 5xx), inside a try block:
try:
resposta = requests.post(url, json=novo_cliente, timeout=10)
resposta.raise_for_status()
print("Cliente criado:", resposta.json())
except requests.exceptions.HTTPError as erro:
print("A API devolveu um erro:", erro)
except requests.exceptions.RequestException as erro:
print("Falha de ligação:", erro)
This way, you clearly tell apart an error returned by the API (for example, 400 Bad Request when fields are missing) from a network problem, such as a timeout or a DNS failure.
Check the result
Since we are using httpbin.org/post, the response returns everything we sent inside a json field. If you see your fields (nome, email and plano) reflected in the response, together with a 200 code, then the send worked. On a real API, also confirm that the new record appears in the database or in the service's dashboard.
Conclusion
With just a few lines and the requests library, you can already send data to any REST API with a POST request, read the response and handle the most frequent errors. A good next step is to learn how to authenticate your requests with a token in the Authorization header, so you can work with private APIs. Which will be the first API you send your data to?