An API (Application Programming Interface) allows different software applications to communicate with each other. Python can use APIs to request data from web services and can also be used to create APIs.
An API is a set of rules and interfaces that allows one program to communicate with another program or service.
For example, a weather application can use a weather API to request current weather information from a server.
Python Application
|
| API Request
↓
Web Server
|
| API Response
↓
Python Application
APIs allow applications to use data and functionality provided by other systems.
A Web API is an API that communicates over the web, usually using HTTP or HTTPS.
A Python program can send an HTTP request to an API endpoint and receive a response from the server.
Client → HTTP Request → API Server
Client ← HTTP Response ← API Server
An endpoint is a URL through which an API provides a particular resource or operation.
https://api.example.com/users
For example, an API might provide separate endpoints for users, products and orders.
/users
/products
/orders
Web APIs commonly use HTTP methods to describe the operation being requested.
| Method | Common Purpose |
|---|---|
| GET | Retrieve data |
| POST | Create or submit data |
| PUT | Replace or update a resource |
| PATCH | Partially update a resource |
| DELETE | Delete a resource |
A GET request is commonly used to retrieve information from a server.
GET /users
In Python, the requests library can be used to send HTTP
requests.
import requests
response = requests.get(
"https://api.example.com/users"
)
print(response.status_code)
An API server returns a response to the client. The response usually contains a status code and data.
response = requests.get(
"https://api.example.com/users"
)
print(response.status_code)
print(response.text)
HTTP status codes tell us whether a request was successful or whether there was a problem.
| Status Code | Meaning |
|---|---|
| 200 | OK / Successful request |
| 201 | Resource created |
| 400 | Bad request |
| 401 | Authentication required or failed |
| 403 | Forbidden |
| 404 | Resource not found |
| 500 | Server error |
import requests
response = requests.get(
"https://api.example.com/users"
)
if response.status_code == 200:
print("Request successful")
else:
print("Request failed")
JSON stands for JavaScript Object Notation. It is a commonly used format for exchanging structured data between applications.
{
"name": "Rahul",
"age": 22,
"course": "Python"
}
JSON objects are commonly represented as Python dictionaries after being decoded.
The json() method of a compatible HTTP response can decode a
JSON response into Python data.
import requests
response = requests.get(
"https://api.example.com/user"
)
data = response.json()
print(data)
data = {
"name": "Rahul",
"age": 22,
"course": "Python"
}
print(data["name"])
print(data["course"])
Rahul Python
Query parameters are values added to a URL to provide additional information to an API.
https://api.example.com/users?city=Patna
The requests library allows query parameters to be passed
using the params argument.
import requests
params = {
"city": "Patna"
}
response = requests.get(
"https://api.example.com/users",
params=params
)
print(response.url)
A POST request is commonly used to send data to an API.
import requests
data = {
"name": "Rahul",
"course": "Python"
}
response = requests.post(
"https://api.example.com/users",
json=data
)
print(response.status_code)
The json argument sends the Python data as JSON.
PUT is commonly used when a client wants to replace or update a resource.
import requests
data = {
"name": "Rahul",
"course": "Python Full Stack"
}
response = requests.put(
"https://api.example.com/users/1",
json=data
)
print(response.status_code)
PATCH is commonly used when only part of a resource needs to be updated.
import requests
data = {
"course": "Python"
}
response = requests.patch(
"https://api.example.com/users/1",
json=data
)
print(response.status_code)
DELETE is commonly used to remove a resource from an API.
import requests
response = requests.delete(
"https://api.example.com/users/1"
)
print(response.status_code)
HTTP headers provide additional information about a request or response. They are commonly used for content types, authentication tokens and other metadata.
import requests
headers = {
"Authorization": "Bearer YOUR_TOKEN",
"Accept": "application/json"
}
response = requests.get(
"https://api.example.com/users",
headers=headers
)
print(response.status_code)
Some APIs require authentication before they allow access to protected resources.
Common authentication approaches include:
headers = {
"Authorization": "Bearer YOUR_TOKEN"
}
response = requests.get(
"https://api.example.com/profile",
headers=headers
)
A timeout prevents a program from waiting indefinitely for a server response.
import requests
response = requests.get(
"https://api.example.com/users",
timeout=10
)
print(response.status_code)
The timeout value is specified in seconds.
Network errors, invalid URLs, timeouts and unsuccessful HTTP responses should be handled appropriately.
import requests
try:
response = requests.get(
"https://api.example.com/users",
timeout=10
)
response.raise_for_status()
data = response.json()
print(data)
except requests.exceptions.RequestException as error:
print("Request error:", error)
The raise_for_status() method raises an exception for HTTP
error responses.
Response headers contain metadata returned by the server.
import requests
response = requests.get(
"https://api.example.com/users"
)
print(response.headers)
A specific header can be accessed using its name.
print(response.headers.get("Content-Type"))
Python dictionaries are convenient when preparing structured JSON data.
student = {
"name": "Amit",
"age": 21,
"course": "Python",
"fees": 15000
}
print(student["name"])
print(student["course"])
Amit Python
REST (Representational State Transfer) is a commonly used architectural style for web APIs.
REST-style APIs commonly use HTTP methods and resource-based URLs.
GET /students
GET /students/10
POST /students
PUT /students/10
DELETE /students/10
The exact behavior of an API depends on its documentation.
API documentation explains how to use an API. It normally contains:
import requests
url = "https://api.example.com/students"
try:
response = requests.get(
url,
timeout=10
)
response.raise_for_status()
students = response.json()
for student in students:
print(student)
except requests.exceptions.RequestException as error:
print("API Error:", error)
requests library can be used to make HTTP requests.Question: Which HTTP method is commonly used to retrieve data from an API?