Working with APIs (Application Programming Interfaces) means allowing different software systems to communicate with each other.
APIs enable applications to send requests and receive responses, usually in JSON format.
Example:
A weather app uses an API to get live weather data from a server.
What is an API?
An API is a bridge between two systems.
Client β Sends request
Server β Processes request
Server β Sends response
Most modern APIs use:
HTTP protocol
JSON data format
How APIs Work
- Client sends a request (GET, POST, etc.)
- Server processes the request
- Server sends a response (usually JSON)
- Client uses the response data
Example API response (JSON):
{
“name”: “Ali”,
“age”: 25
}
Common HTTP Methods
GET β Retrieve data
POST β Create new data
PUT β Update existing data
PATCH β Partially update data
DELETE β Remove data
These are used when interacting with REST APIs.
API Endpoints
An endpoint is a specific URL where API requests are sent.
Example:
GET /users
POST /users
GET /users/1
Each endpoint performs a specific function.
Working with APIs in Python
You can use the requests library.
Install:
pip install requests
Example:
import requestsresponse = requests.get("https://api.example.com/users")data = response.json()print(data)
Sending Data Using POST
import requestsdata = {
"name": "Ali",
"age": 25
}response = requests.post("https://api.example.com/users", json=data)print(response.json())
Handling API Responses
Important response properties:
response.status_code β HTTP status
response.json() β Get JSON data
response.text β Raw text
Common Status Codes:
200 β Success
201 β Created
400 β Bad request
401 β Unauthorized
404 β Not found
500 β Server error
Authentication in APIs
Many APIs require authentication.
Common methods:
API Key
Token Authentication
JWT
OAuth
Example with token:
headers = {
"Authorization": "Token your_token_here"
}response = requests.get("https://api.example.com/data", headers=headers)
Error Handling
Always handle errors:
if response.status_code == 200:
print(response.json())
else:
print("Error:", response.status_code)
Real-World Uses of APIs
Payment gateways
Weather apps
Social media integrations
AI services
Database services
Cloud platforms
APIs power modern web and mobile applications.
Best Practices When Working with APIs
Check documentation
Handle errors properly
Secure your API keys
Use HTTPS
Validate responses
Respect rate limits
Key Takeaway
Working with APIs allows applications to communicate and exchange data efficiently.
Understanding HTTP methods, endpoints, authentication, and JSON handling is essential for modern backend and frontend development.