python requests quickstart

hljs.initHighlightingOnLoad();

Python Requests Quickstart

If you are looking to make HTTP requests in Python, the requests library is a popular choice. It is a simple and elegant way to make HTTP requests with Python.

Installation

You can install the requests library using pip:

pip install requests

Basic Usage

Here is an example of how to make a GET request using requests:

import requests

response = requests.get('https://www.example.com')
print(response.status_code)
print(response.text)
  • The get function sends a GET request to the specified URL.
  • The status_code attribute returns the HTTP status code of the response.
  • The text attribute returns the content of the response as a string.

If you need to send data with your request, you can use the data parameter:

import requests

payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://www.example.com', params=payload)
print(response.url)
  • The params parameter is used to pass data with the request.
  • The url attribute returns the URL of the response.

If you need to send JSON data with your request, you can use the json parameter:

import requests

payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://www.example.com', json=payload)
print(response.status_code)
  • The post function sends a POST request to the specified URL.
  • The json parameter is used to send JSON data with the request.

Error Handling

If there is an error with your request, requests will raise an exception. Here is an example of how to handle errors:

import requests

try:
    response = requests.get('https://www.example.com')
    response.raise_for_status()
except requests.exceptions.HTTPError as err:
    print(err)
  • The raise_for_status function will raise an exception if the HTTP status code is not successful.