1. What is an API?

- API (Application Programming Interface): A way for applications to communicate with each other.
- In Python, APIs are often accessed over the web using HTTP requests.
- Data is usually returned in JSON format.
2. The requests
Library
The most common library for working with APIs in Python.
Install if needed:
pip install requests
3. Making a GET Request
import requests
response = requests.get("https://api.github.com/users/octocat")
# Status code
print("Status:", response.status_code)
# Response as JSON
data = response.json()
print("Username:", data["login"])
print("Public Repos:", data["public_repos"])
✅ GET requests are used to retrieve data.
4. Making a POST Request
import requests
url = "https://jsonplaceholder.typicode.com/posts"
payload = {
"title": "My First Post",
"body": "Hello, this is a test post.",
"userId": 1
}
response = requests.post(url, json=payload)
print("Status:", response.status_code)
print("Response:", response.json())
✅ POST requests are used to send data.
5. Handling Authentication
Some APIs require authentication (API key, token, etc.).
headers = {
"Authorization": "Bearer YOUR_API_KEY"
}
response = requests.get("https://api.example.com/data", headers=headers)
print(response.json())
6. Common HTTP Status Codes
Code | Meaning |
---|---|
200 | Success |
201 | Resource created |
400 | Bad request |
401 | Unauthorized (need API key/token) |
403 | Forbidden |
404 | Not found |
500 | Server error |
7. Example: Weather API
import requests
API_KEY = "your_api_key"
city = "London"
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric"
response = requests.get(url)
data = response.json()
print("City:", data["name"])
print("Temperature:", data["main"]["temp"], "°C")
print("Weather:", data["weather"][0]["description"])
8. Best Practices
- Always check
response.status_code
before using data. - Handle errors with
try/except
. - Avoid exposing your API keys (use environment variables).
- Respect API rate limits.
Summary
- APIs allow Python to communicate with web services.
- Use the
requests
library to make GET and POST requests. - Most APIs return JSON, which you can parse with
.json()
. - Authentication (API keys, tokens) is often required.
- Always handle status codes and possible errors.