How to Use Requests Module in Python: Simple Guide
Use the
requests module in Python to send HTTP requests like GET or POST by calling functions such as requests.get() or requests.post(). Import the module first, then call these functions with the URL and optional parameters to get the server response.Syntax
The requests module provides simple functions to send HTTP requests. The most common are:
requests.get(url, params=None, headers=None): Sends a GET request to the specified URL.requests.post(url, data=None, json=None, headers=None): Sends a POST request with optional data.response.status_code: The HTTP status code returned by the server.response.text: The content of the response as a string.
You start by importing the module, then call these functions with the URL and any needed data.
python
import requests response = requests.get('https://example.com') print(response.status_code) print(response.text)
Example
This example shows how to send a GET request to a website and print the status code and first 100 characters of the response content.
python
import requests response = requests.get('https://httpbin.org/get') print('Status code:', response.status_code) print('Response content:', response.text[:100])
Output
Status code: 200
Response content: {
"args": {},
"headers": {
"Accept": "*/*",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.31.0"
},
"origin": "
Common Pitfalls
Common mistakes when using requests include:
- Not importing the module before use.
- Forgetting to check the
status_codeto ensure the request succeeded. - Passing data incorrectly in POST requests (use
data=for form data,json=for JSON). - Not handling exceptions like connection errors.
Always check the response and handle errors to avoid crashes.
python
import requests # Wrong: forgetting to import # response = requests.get('https://example.com') # This will cause an error # Right way: try: response = requests.get('https://example.com') if response.status_code == 200: print('Success!') else: print('Failed with status:', response.status_code) except requests.exceptions.RequestException as e: print('Error:', e)
Output
Success!
Quick Reference
| Function | Purpose | Common Parameters |
|---|---|---|
| requests.get(url, params=None, headers=None) | Send a GET request | url (str), params (dict), headers (dict) |
| requests.post(url, data=None, json=None, headers=None) | Send a POST request | url (str), data (dict), json (dict), headers (dict) |
| response.status_code | HTTP status code of response | N/A |
| response.text | Response content as string | N/A |
| requests.exceptions.RequestException | Base exception for request errors | N/A |
Key Takeaways
Import the requests module before using its functions.
Use requests.get() for GET requests and requests.post() for POST requests.
Always check response.status_code to confirm success.
Handle exceptions to manage connection errors gracefully.
Use response.text to access the content returned by the server.