SoFunction
Updated on 2025-04-11

Python uses the requests library to easily initiate HTTP requests

requests is a very popular third-party library in Python for sending HTTP requests. It provides a concise API, making it very easy to send various HTTP requests (such as GET, POST, PUT, DELETE, etc.).

Here are some basic usage examples:

Install

First, you need to install the requests library. If you haven't installed it, you can use pip to install it:

> pip install requests

Send a GET request

import requests

# mock data url: /
resp = ("/posts/3")

if resp.status_code == 200:
    # Get response content (JSON format)    data = ()
    print(data)
else:
    print(f"Request failed,Status code:{resp.status_code}")

Send GET request with parameters

import requests

# mock data url: /
param = {
    "userId": 2
}
resp = ("/posts", params=param)

if resp.status_code == 200:
    # Get response content (JSON format)    data = ()
    print(data)
else:
    print(f"Request failed,Status code:{resp.status_code}")

Send a POST request

import requests

data = {
    "userId": 11,
    "title": "requests post demo",
    "body": "requests post body"
}

resp = ("/posts", data=data)

if resp.status_code == 200 or resp.status_code == 201:
    # Get response content (JSON format)    data = ()
    print(data)
else:
    print(f"Request failed,Status code:{resp.status_code}")

Set request header

import requests
import json

# mock data url: /
data = {
    "userId": 11,
    "title": "requests post demo",
    "body": "requests post body"
}
header = {
    'Content-Type': 'application/json_demo'
}
resp = ("/posts", data=(data), headers=header)

if resp.status_code == 200 or resp.status_code == 201:
    # Get response content (JSON format)    data = ()
    print(data)
else:
    print(f"Request failed,Status code:{resp.status_code}")

Setting and getting cookies

import requests

# mock data url: /
cookies = {
    'session_id': '12345',
    'user_token': 'abcdef'
}

# Send a request and bring cookiesresp = ("/posts/1", cookies=cookies)

# Get cookies from the responsecookies = .get_dict()
print(cookies)

Manage cookies with Session

Objects are especially useful when you need to keep cookies across multiple requests. It allows you to automatically store and send cookies during a session.

import requests

# Create a session objectsession = ()

# Send the first request, the server may set some cookiesresponse = ('/login')

# Send a second request, this request will automatically bring the cookies set before.response = ('/profile')

# You can check cookies in responseprint(.get_dict())

Processing response

response.status_code: HTTP status code

: String form of response content

: The binary form of the response content

(): parse the response content into a JSON object (provided that the response content is in JSON format)

Exception handling

When sending a request, you may encounter various exceptions, such as network problems, invalid URLs, etc.

These exceptions can be caught using the try-except block:

import requests

try:
    response = ('/data')
    response.raise_for_status()  # If the response status code is not 200, an HTTPError exception is raised    data = ()
    print(data)
except  as errh:
    print(f"HTTP mistake:{errh}")
except  as errc:
    print(f"连接mistake:{errc}")
except  as errt:
    print(f"Request timeout:{errt}")
except  as err:
    print(f"请求mistake:{err}")

Print complete request and response packets containing headers

import http
import logging
import requests

# Configure logging(level=)
('requests').setLevel()
 = 1

# mock data url: /
resp = ("/posts/3")

if resp.status_code == 200:
    # Get response content (JSON format)    data = ()
    print(data)
else:
    print(f"Request failed,Status code:{resp.status_code}")

This is the article about python using the requests library to easily initiate HTTP requests. For more related contents for python requests, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!