python requests post

Python Requests Post

If you're familiar with Python, you might know that it has a module called "requests" which allows you to send HTTP/1.1 requests using Python. You can use the HTTP request methods (GET, POST, PUT, DELETE, etc.) to send requests to a server and receive a response.

Here, I will specifically talk about the "requests.post(url, data=None, json=None, **kwargs)" method which sends a POST request to the specified URL with the data as the request body. The data can be a dictionary or a list of tuples representing the key-value pairs.


import requests

url = 'https://jsonplaceholder.typicode.com/posts'
data = {'title': 'foo', 'body': 'bar', 'userId': 1}

response = requests.post(url, data=data)

print(response.json())
  

In the above example, we're sending a POST request to the URL "https://jsonplaceholder.typicode.com/posts" with the data as the request body. The response we get back is in JSON format which we can access using the ".json()" method.

Alternatively, we can also send the data in JSON format using the "json" parameter instead of "data". Here's an example:


import requests

url = 'https://jsonplaceholder.typicode.com/posts'
data = {'title': 'foo', 'body': 'bar', 'userId': 1}

response = requests.post(url, json=data)

print(response.json())
  

In the above example, we're sending the data in JSON format using the "json" parameter instead of "data". The rest of the code is the same as the previous example.

These are the two most common ways to send a POST request using Python requests. However, there are several other parameters that can be used with the "requests.post()" method such as headers, cookies, timeout, etc. which can be found in the official documentation.