Using Python requests module for GET and POST API calls
This tutorial explains how to install the Python requests library and use it to perform GET and POST HTTP requests, detailing required parameters, headers, and providing complete code examples for calling remote APIs and handling responses.
Follow and star to learn new Python skills daily.
1. Install the requests module
<code>pip install requests</code>2. Use the requests module to perform a GET request
The GET request uses requests.get() with common parameters such as url , params , and headers .
url: the remote API address
params: query parameters
headers: request header information
Example implementation:
<code># -*- coding: utf-8 -*-
import requests
import ast
# API endpoint
url = 'XXX'
# GET parameters
data = {'type':'0'}
# headers
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer XXX'
}
r = requests.get(url, params=data, headers=headers)
# status code
print(r.status_code)
# response text
content = r.text
# convert string to dict
content_list = ast.literal_eval(content)
print(content_list)
# json response
print(r.json())
</code>The script prints the status code, the parsed response dictionary, and the JSON content.
3. Use the requests module to perform a POST request
The POST request uses requests.post() with parameters url , data , and headers .
url: the remote API address
data: POST payload
headers: request header information
Example implementation:
<code># -*- coding: utf-8 -*-
import requests
import ast
# API endpoint
url = 'XXX'
# headers
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer XXX'
}
# POST data
data = {
'nickname': '111',
'gender': 1,
'city': 'ce',
'avatar': '111'
}
r = requests.post(url, data=data, headers=headers)
print(r.status_code)
content = r.text
content_list = ast.literal_eval(content)
print(content_list)
print(r.json())
</code>These examples demonstrate how to use the Python requests library for both GET and POST API calls.
Disclaimer: This article is compiled from the internet; copyright belongs to the original author.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.