Master Python’s Requests: Quick Guide to GET and POST API Calls

This tutorial shows how to install the Python requests library and use it to perform GET and POST HTTP requests, covering required parameters, headers, and example code for handling responses.

21CTO
21CTO
21CTO
Master Python’s Requests: Quick Guide to GET and POST API Calls

In Python we can use the requests module to call remote APIs.

1. Install the requests module

pip install requests

2. Use requests to make GET requests

GET requests are performed with requests.get(), which commonly takes url, params, and headers arguments.

url : the remote API endpoint

params : query parameters

headers : request headers

A simple GET example:

# -*- coding: utf-8 -*-
import requests
import ast
# API endpoint
url = 'XXX'
# query parameters
data = {'type':'0'}
# headers
headers = {
  'Content-Type': 'application/x-www-form-urlencoded',
  'Authorization': 'Bearer XXX'
}
r = requests.get(url, params=data, headers=headers)
print(r.status_code)
content = r.text
content_list = ast.literal_eval(content)
print(content_list)
print(r.json())

This demonstrates how to perform a GET request and process the response.

3. Use requests to make POST requests

POST requests use requests.post(), typically with url, data, and headers arguments.

url : the remote API endpoint

data : form data to send

headers : request headers

A simple POST example:

# -*- coding: utf-8 -*-
import requests
import ast
url = 'XXX'
headers = {
  'Content-Type': 'application/x-www-form-urlencoded',
  'Authorization': 'Bearer XXX'
}
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())

This shows how to send a POST request and handle the JSON response.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonHTTPAPIrequestsgetPOST
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.