requests
is a Python library that makes it easy to send HTTP requests using Python. It provides a convenient interface for working with HTTP requests, abstracting away the complexities of making requests behind a beautiful, simple API.
To use requests
, you first need to install it using pip
, the Python package manager. You can do this by running the following command:
pip install requests
Once requests
is installed, you can start using it in your Python code by importing it like this:
import requests
To send an HTTP request using requests
, you can use one of the following functions:
requests.get(url)
: Sends a GET request to the specifiedurl
.requests.post(url, data)
: Sends a POST request to the specifiedurl
with the specifieddata
as the request body.requests.put(url, data)
: Sends a PUT request to the specifiedurl
with the specifieddata
as the request body.requests.delete(url)
: Sends a DELETE request to the specifiedurl
.
Here’s an example of how to use requests
to send a GET request to the GitHub API to retrieve information about a specific user:
import requests
# Make a GET request to the GitHub API to retrieve information about a user
response = requests.get('https://api.github.com/users/<username>')
# The response from the server is stored in the 'response' variable
# You can access the status code of the response using 'response.status_code'
# You can access the content of the response using 'response.content'
The response
object returned by requests
has several useful attributes and methods that you can use to work with the response data. Some of the most commonly used ones are:
response.status_code
: The HTTP status code of the response (e.g. 200 for a successful request, 404 for a resource not found).response.headers
: A dictionary-like object containing the response headers.response.text
: The content of the response as a Unicode string.response.json()
: If the response content is in JSON format, this method returns the parsed JSON data as a Python dictionary.
For more information, you can check out the requests
documentation: https://requests.readthedocs.io/en/latest/