What is the Python Requests library?
The Requests Library is a library for sending HTTP requests in Python, developed initially by Kenneth Reitz. Because of its simplicity and ease of use has become the standard way to send HTTP POST and GET requests (and other types), although it is not included in the Python distribution. The Requests Library is based on the urllib3 library and hides the complexity of making HTTP requests behind a simple API. The Requests Library supports SSL connections, international domain names, and session cookies. It automatically encodes POST data, formats JSON, decompresses server responses, and has built-in proxy support. A complete list of features can be found on the official Requests Library site.
What is JSON?
JavaScript Object Notation (JSON) is a language-independent text format for storing and exchanging data. Web applications use JSON to exchange data between a web browser and a server and exchange data between servers via REST API. For many programming languages, including JavaScript, Java, C ++, C #, Go, PHP, Python, there are ready-made code libraries for creating and manipulating JSON data. JSON file names use the .json file extension.
What is HTTP POST?
HTTP POST method requests the webserver to accept the data enclosed in the POST request message body to process or store it. The POST method is used to upload files and submit web forms. The POST is one of the nine standard methods of the HTTP protocol. The POST method is used for CRUD operations to create or update a resource on the server. POST requests can change the server's state and are not idempotent, unlike GET and HEAD requests.
How to use the Python Requests library?
To install the Python Requests library, run the following command:
After installing the Request Library, you can use it in your application.
Python Requests POST method syntax
Python Requests method syntax for making POST requests:
Where:
- URL: target URL/API enpoint.
- data (optional): can be a dictionary, a list of tuples, bytes, or a file to send in the body of the POST request.
- json (optional): a dictionary that will be converted to a JSON string and included in the body of the POST request.
- arguments (optional): the arguments that the POST request accepts.
How to make a POST request with Python?
To make a POST request using Requests library, you need to call the requests.post() method and pass the data with the the data= or json= parameter.
How to send custom HTTP headers with a POST request?
HTTP headers can be passed to a POST request using the headers= parameter.
Python Requests POST JSON Example
An example of sending JSON with using the Python Requests library to the ReqBin echo URL:
The server response to our POST JSON request: