Python Requests library: Make HTTP requests elegant
Requests is one of the most popular HTTP libraries in the Python ecosystem. Its design philosophy is "HTTP for Humans" - simple and intuitive, allowing you to focus on business logic rather than tedious network details. Compared to the built-inurllib, the interface of Requests is more user-friendly and can easily handle various HTTP requests and responses.
Whether you are developing crawlers, calling RESTful APIs, or need to interact with third-party services, Requests can greatly improve your development efficiency.
1. Installation and Startup
Use pip to complete the installation:
If you are using the Anaconda environment, Requests usually comes pre-installed. If you encounter permission issues, you can add--userParameters or run pip in a virtual environment:
Tip: Recommended in a virtual environment (such as
venv、conda) to avoid polluting system-level Python.
Once installed, the import library is ready to use:
2. Send the first GET request
The most common operation in HTTP is the GET request, which is used to obtain resources. It only takes one line of code to make a request:
After the request is completed, what we are most concerned about is usually the status code and response content:
.status_code: HTTP status code,200represents success,404means not found,500It's a server error etc..text: The automatically decoded text content of Requests is usually a readable string.
2.1 Carrying query parameters
Many APIs require passing query string parameters. Requests can receive a dictionary and automatically concatenate it into URL parameters:
This way I don’t have to manually splice?q=python&page=1, which is both clear and avoids encoding problems.
3. Processing of response content
Requests provides multiple ways to extract response data, suitable for different scenarios:
.content:returnbytes, suitable for processing binary files such as images and PDFs..text: Returns a string, Requests will be based on the response header orencodingProperties are automatically decoded..json(): If the response body is in JSON format, you can directly call this method to get the Python data structure, eliminating the need to manuallyjson.loads()。
4. Custom request header
Many scenarios require disguising User-Agent or adding authentication tokens, etc. passheadersParameters can be easily set:
The case of keys in Headers does not matter, Requests are automatically processed into standard format.
5. Send POST request
POST requests are used to submit data, such as login, form submission, or resource creation.
5.1 Form data
submitapplication/x-www-form-urlencodedFormatted data (emulates HTML form):
5.2 Submit JSON data
Nowadays, most REST APIs use JSON and can be used directlyjsonParameters, Requests will be set automaticallyContent-Type: application/json:
5.3 File upload
When uploading files, usefilesparameters, and open the file in binary mode:
Notice'rb'mode, otherwise the file may be corrupted due to encoding issues.filesThe dictionary supports uploading multiple files at the same time.
6. Other HTTP methods
Requests provides corresponding shortcut functions for common HTTP methods:
These methods are used withget()andpost()Highly consistent and common parameters.
7. Response headers and Cookies
7.1 View response headers
Response headers are stored in dictionary form inresponse.headers, keys are not case-sensitive:
7.2 Handling Cookies
Cookies returned by the server can be passedresponse.cookiesAccess; custom cookies can also be carried when sending requests:
8. Timeout control
Network requests may remain blocked due to network fluctuations or server unresponsiveness. set uptimeoutYou can limit the waiting time to avoid program freezes:
It is recommended to explicitly set the timeout in all requests to improve the robustness of the program.
9. Maintain session: Session object
If you need to request the same website multiple times and keep logged in status or common request headers, you can useSessionObject:
SessionThe bottom layer uses a connection pool and reuses TCP connections across requests to improve performance.
10. Quick overview of advanced functions
10.1 Redirect processing
By default, Requests automatically follow 3xx redirects. If you want to disable automatic jump, you can setallow_redirects=False:
10.2 Using a proxy
passproxiesParameter configuration HTTP/HTTPS proxy:
10.3 SSL Certificate Verification
Requests verifies SSL certificates by default when accessing HTTPS sites. If you encounter a self-signed certificate in a development environment, you can temporarily turn off verification (Do not do this in a production environment), or specify a custom CA certificate:
11. Best practices for error handling
Abnormalities are inevitable in network operations. Perfect error handling can make the program more reliable:
raise_for_status()Will be thrown when status code is 4xx or 5xxHTTPError, eliminating manual inspection.- All Requests exceptions inherit from
requests.exceptions.RequestException。
12. Performance optimization tips
12.1 Streaming download of large files
When downloading large files, usestream=TrueYou can write to disk while downloading to avoid loading into memory at once:
12.2 Adjust connection pool
by customizingHTTPAdapter, you can control the connection pool size and retry strategy:
This is very useful for high concurrent request scenarios.
13. Summary
Requests encapsulates the complexity of HTTP behind a simple API, allowing you to:
- Use very few codes to complete common operations such as GET and POST;
- Easily handle JSON, file uploads, cookies and headers;
- Maintain login status and reuse connections through Session;
- Use mechanisms such as timeout, exception-handling, and streaming requests to build stable network programs.
After mastering these core functions, you can use Requests comfortably in actual projects. If you want to explore further, it is recommended to consult the official documentation and the "HTTP Definitive Guide" to understand the underlying protocol - of course, Requests is elegant and powerful enough for daily development.

