Python Requests library usage tutorial: Say goodbye to the cumbersomeness of urllib
Are you still using the Python built-inurllibAre you having headaches with complex coding splicing, certificate configuration, and multi-session management? Today we will talk about Requests, the most popular HTTP client library in the Python ecosystem. It uses a minimalist API to encapsulate almost all HTTP functions needed for daily development. The threshold for getting started is extremely low, but the efficiency is very high.
1. Introduction
The official slogan of Requests is "HTTP for Humans (HTTP library designed for humans)", which is no exaggeration at all:
- Built-in common functions such as automatic encoding and decoding, JSON parsing, status code checking, etc.
- Supports connection retention pooling, cookie persistence, and file upload/download in chunks
- Handling exceptions, setting timeouts, proxies, and authentication all require just one line of parameters
Whether you are calling external APIs, writing crawlers, or doing interface testing, Requests can help you get twice the result with half the effort.
2. Installation
Just one command to do it (supports Python 3.7+). It is recommended to install in a virtual environment and keep project dependencies clean:
After the installation is complete, you can import it directly in the code and use it:
3. Basic usage: Get started in one minute
Requests supports all standard HTTP methods. Let’s start with the most commonly used ones.GETandPOSTGet started, and then take a quick look at other methods.
Send GET request
callrequests.get()And pass in the target URL, the returnedResponseThe object contains all response information:
Send POST request
When submitting a form or simple data, use it directlydataParameters, Requests will be set automaticallyContent-Type:
Other standard HTTP methods
PUT、DELETE、HEAD、OPTIONSThe other methods are equally simple, and their usage is the same asGET / POSTBe consistent:
4. Request parameters: customize your request as you like
In real projects, we often need to splice URL parameters, customize request headers, or send JSON data. Requests uses a few keyword parameters to make these operations extremely refreshing.
Pass URL parameters
Put the parameters into a dictionary and pass it toparams, Requests will automatically complete URL encoding and splicing:
💡 Tips: If the parameter value is empty or
None, Requests will ignore this parameter and will not carry it in the URL.
Custom request header
To simulate browser access, add API Token, set Accept type and other scenarios, just pass in a dictionary toheadersparameter:
Send JSON data
More and more APIs require the use of request bodies in JSON format, and Requests specifically providesjsonParameters, no need to do it manuallyjson.dumps()and settingsContent-Type:
5. Response processing: quickly extract useful information
ResponseThe object is very well encapsulated. According to different needs, you can choose the most appropriate attributes to obtain the response content.
Get response content
Example:
⚠️ If the response is not valid JSON,
response.json()will throwjson.JSONDecodeError, it is recommended to placetry-exceptused in blocks.
Check status code
response.status_code: Get the digital status code directlyresponse.raise_for_status(): Automatically determine the status code and throw it when it is not 2xxHTTPErrorabnormal
Get response headers
response.headersIt is a dictionary-like object, and the keys are not case-sensitive, so it is very convenient to use:
6. Advanced functions: easily handle complex scenarios
Session object (Session): reused connections and persistent cookies
When you need to send multiple requests to the same website,SessionThe object can reuse TCP connections, significantly improving performance; at the same time, it will also automatically manage and carry Cookies, eliminating the trouble of manually handling Cookies:
✅ You can also use
with requests.Session() as session:syntax to avoid forgetting to close.
SSL Verification
By default Requests will verify the SSL certificate to ensure a secure connection. If you encounter a self-signed certificate or development environment, you can also flexibly control the verification behavior:
Timeout settings
**Be sure to set a timeout! ** Otherwise, the program may wait indefinitely due to network fluctuations. Requests supports two timeout methods:
- tuple
(connect_timeout, read_timeout): Set connection timeout and read timeout respectively - single number: total timeout (connect + read)
7. Error handling: gracefully deal with various accidents
Requests encapsulates common network and HTTP errors into exception classes, using a clear exception tree structure. It is strongly recommended to catch specific exception types rather than just the parent class of all exceptions:
This way your program won't crash easily due to a network jitter.
8. Best Practice: Write Robust and Elegant Code
- Timeout must be set - to prevent the program from hanging indefinitely, especially in a production environment
- Priority to use Session - can improve performance and automatically manage cookies in multi-request scenarios
- Develop and use
raise_for_status()Habit - automatically detect 4xx/5xx and use it with exception-handling - Enable streaming downloads when processing large files - avoid loading the entire file into memory at once (
stream=True) - Catch specific exceptions - Don’t just use
RequestExceptionOne pot for easy debugging and targeted processing - Comply with the website’s
robots.txt——Crawler development must be friendly - Sensitive information is stored in environment variables - API Tokens, passwords, etc. must not be hard-coded. Use
os.getenv()or.envFile management
9. Summary
Requests is the most recommended HTTP client library in the Python ecosystem. It uses an intuitive API to solve the problem.urlliball pain points. Whether it is a simple interface call or complex communication between crawlers and microservices, Requests allows you to complete the most work with the least code.
If you also want to explore more advanced features (file uploads, streaming requests, proxy settings, OAuth authentication, etc.), please visit Requests 官方文档, which has rich examples and detailed instructions. Now, just usepip install requestsStart your journey to efficient HTTP!

