Working with REST APIs in Python
Python REST API integration with GET, POST, PUT, DELETE examples using requests library
In today’s digital world, most applications communicate with each other using REST APIs (Representational State Transfer Application Programming Interfaces). Python, with its simple syntax and powerful libraries, makes it easy to consume and interact with REST APIs for data exchange, automation, and integration.
In this article, we’ll explore what REST APIs are, how to use them in Python, and provide examples with popular libraries.
A REST API allows communication between a client (like a Python program) and a server using HTTP methods:
GET → Retrieve data from the server
POST → Send new data to the server
PUT/PATCH → Update existing data
DELETE → Remove data
Most modern web services (like Twitter, GitHub, and Google APIs) provide REST endpoints.
requests – The most widely used library for making HTTP requests.
httpx – Modern async-capable HTTP client.
urllib – Python’s built-in HTTP library.
aiohttp – For asynchronous API requests.
The requests
library makes it easy to fetch data from an API.
import requests
# Example: Fetching data from JSONPlaceholder API
url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.get(url)
# Print status and data
print("Status Code:", response.status_code)
print("Response JSON:", response.json())
This fetches a sample blog post from a free API.
import requests
url = "https://jsonplaceholder.typicode.com/posts"
data = {
"title": "Python API Example",
"body": "Learning REST API with Python!",
"userId": 1
}
response = requests.post(url, json=data)
print("Status Code:", response.status_code)
print("Response JSON:", response.json())
This sends new data to the API.
import requests
url = "https://jsonplaceholder.typicode.com/posts/1"
data = {
"title": "Updated Title",
"body": "Updated content using PUT request.",
"userId": 1
}
response = requests.put(url, json=data)
print("Updated Data:", response.json())
import requests
url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.delete(url)
print("Status Code:", response.status_code)
Handle errors – Check status_code
before processing data.
Use authentication – Many APIs require API keys or OAuth.
Rate limits – Respect API rate limits to avoid blocking.
Use environment variables – Store API keys securely.
Consider async requests – For large-scale data fetching, use httpx
or aiohttp
.
Weather apps – Fetch weather data from OpenWeather API.
Finance apps – Get stock prices from Yahoo Finance API.
Social media – Automate posting and data collection from Twitter API.
Machine learning – Collect training data from various APIs.
Working with REST APIs in Python is an essential skill for modern developers. By mastering libraries like requests
and understanding GET, POST, PUT, and DELETE methods, you can integrate Python with powerful web services and build data-driven applications with ease.