python requests post with parameters

Python Requests Post with Parameters

If you want to send some data to a server using HTTP/HTTPS protocol, you need to use the POST method. Python provides a library called requests which makes it easy to send HTTP/HTTPS requests using Python.

Using Requests Library to Send POST Request

In order to send a POST request using the requests library, you can use the requests.post() method. The method takes two arguments: the URL to which the request has to be sent and a dictionary of parameters that have to be sent with the request. The dictionary of parameters can be created using Python's built-in dict object.


import requests
url = 'https://example.com/api'
params = {
    'key1': 'value1',
    'key2': 'value2'
}
response = requests.post(url, data=params)
print(response.text)

In the example code above, we are sending a POST request to the URL https://example.com/api with two parameters: key1 and key2 with their respective values. The response.text attribute contains the content of the response received from the server.

Sending Parameters as JSON

Sometimes, you may need to send parameters as JSON instead of as a dictionary. In that case, you can use the json parameter in the requests.post() method.


import requests
url = 'https://example.com/api'
params = {
    'key1': 'value1',
    'key2': 'value2'
}
response = requests.post(url, json=params)
print(response.text)

The above code sends the same parameters as in the previous example, but in JSON format instead of a dictionary.

Sending Parameters in URL

Sometimes, you may need to send parameters in the URL itself instead of as part of the request body. In such cases, you can append the parameters to the URL using the params parameter in the requests.post() method.


import requests
url = 'https://example.com/api'
params = {
    'key1': 'value1',
    'key2': 'value2'
}
response = requests.post(url, params=params)
print(response.text)

The above code sends the same parameters as in the previous examples, but as part of the URL itself.

Conclusion

In this article, we have seen how to send POST requests with parameters using the requests library in Python. We have also seen how to send parameters as a dictionary, as JSON, and as part of the URL itself.