ch11s1_WhatAreAPIs
APIs (Application Programming Interfaces) are **bridges that let software systems talk to each other**.
Chapter 11: Working with APIs β What Are APIs?
π What Are APIs? β Understanding Application Programming Interfaces
APIs (Application Programming Interfaces) are bridges that let software systems talk to each other.
They define how programs can request and exchange data, making integration between services simple and standardized.
π§© 1. Real-World Analogy
Think of an API like a restaurant menu:
- The menu (API documentation) lists what you can order (available actions).
- The waiter (API server) takes your order and delivers it to the kitchen (backend system).
- You donβt see how the food is made β you just get the result.
Thatβs exactly how applications communicate β through structured requests and responses.
π§ 2. Why APIs Matter
| Benefit | Description |
|---|---|
| Modularity | Allows applications to use external services (e.g., Google Maps API). |
| Integration | Enables different systems to share data and functionality. |
| Automation | Powers bots, data pipelines, and cloud orchestration. |
| Scalability | Lets developers build on top of existing ecosystems (e.g., GitHub API). |
APIs are the backbone of modern web and mobile development β from social apps to IoT systems.
π 3. Types of APIs
| Type | Description | Example |
|---|---|---|
| Public API | Open to everyone with documentation | OpenWeatherMap, NASA API |
| Private API | Used internally by organizations | Company microservices |
| Partner API | Shared with selected partners | Payment gateway APIs |
| REST API | Uses HTTP methods to access data | GET /users, POST /orders |
| GraphQL API | Query language for APIs | Facebook GraphQL |
| WebSocket API | Enables real-time communication | Chat, stock updates |
π§± 4. Anatomy of an API Request
Most APIs use HTTP β the same protocol your browser uses.
| Part | Example | Description |
|---|---|---|
| Endpoint (URL) | https://api.example.com/users | API address |
| Method | GET, POST, PUT, DELETE | Type of action |
| Headers | Authorization: Bearer <token> | Metadata or credentials |
| Body | { "name": "Alice" } | Data sent to the server |
π» 5. Making API Calls in Python
The requests library is the simplest way to interact with APIs.
import requests
url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.get(url)
# Convert JSON to Python dict
data = response.json()
print("Title:", data["title"])
print("Body:", data["body"])
βοΈ 6. Sending Data with POST Requests
Some APIs let you send or create data using POST requests.
import requests
url = "https://jsonplaceholder.typicode.com/posts"
payload = {"title": "New Post", "body": "Hello World", "userId": 1}
response = requests.post(url, json=payload)
print("Status:", response.status_code)
print("Response:", response.json())
β Use
json=payloadinstead ofdata=payloadto automatically send JSON content.
π΅οΈ 7. Adding Headers and Query Parameters
You can pass authentication tokens and query filters easily:
url = "https://api.openweathermap.org/data/2.5/weather"
params = {"q": "London", "appid": "YOUR_API_KEY"}
headers = {"User-Agent": "MyPythonApp/1.0"}
response = requests.get(url, params=params, headers=headers)
print(response.url) # Full request URL
π§ 8. Handling Errors Gracefully
APIs can fail β always check the response.
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
if response.status_code == 200:
print("Success:", response.json())
elif response.status_code == 404:
print("Not Found!")
else:
print("Error:", response.status_code)
| Common Code | Meaning |
|---|---|
200 | Success |
201 | Created |
400 | Bad request |
401 | Unauthorized |
404 | Not found |
500 | Server error |
π 9. Authentication β Accessing Protected APIs
Many APIs require credentials to ensure authorized access.
API Keys
Simplest method β passed as a query parameter or header.
headers = {"Authorization": "Bearer YOUR_TOKEN"}
response = requests.get("https://api.github.com/user", headers=headers)
print(response.json())
π Always store keys securely using environment variables, not in your code.
import os
API_KEY = os.getenv("GITHUB_API_KEY")
π§© 10. Parsing JSON Responses
Most APIs return JSON (JavaScript Object Notation) β easy to use in Python.
data = response.json()
for key, value in data.items():
print(key, ":", value)
You can also serialize data back to JSON:
import json
python_data = {"name": "Alice", "age": 25}
json_string = json.dumps(python_data)
print(json_string)
π§ 11. Comparing REST, GraphQL, and WebSocket APIs
| Feature | REST | GraphQL | WebSocket |
|---|---|---|---|
| Structure | Multiple endpoints | Single endpoint with queries | Persistent connection |
| Data | Fixed responses | Flexible queries | Continuous updates |
| Use Case | CRUD APIs | Data-heavy apps | Real-time data |
π§° 12. Testing and Debugging APIs
| Tool | Use |
|---|---|
| Postman | Visual API testing and documentation |
| curl | Command-line API testing |
| HTTPie | Simple and readable terminal requests |
Example:
curl https://jsonplaceholder.typicode.com/posts/1
π°οΈ 13. Real-World Example β SpaceX Launch API
import requests
url = "https://api.spacexdata.com/v5/launches/latest"
response = requests.get(url)
if response.ok:
data = response.json()
print("Mission:", data["name"])
print("Date:", data["date_utc"])
print("Rocket:", data["rocket"])
π APIs like this power dashboards, mobile apps, and live-tracking tools.
π‘ 14. Best Practices for Using APIs
β
Check API docs and usage limits.
β
Always handle errors and rate limits.
β
Use environment variables for API keys.
β
Cache responses for performance.
β
Respect terms of service and attribution.
β
Test with Postman or curl before writing code.
β
Prefer pagination for large data sets.
π§ Summary
| Concept | Description | Example |
|---|---|---|
| API | Interface that connects software systems | REST, GraphQL |
| HTTP Methods | Define actions to perform | GET, POST, PUT, DELETE |
| Response Codes | Indicate success or failure | 200, 404, 500 |
| Authentication | Protects access | API keys, tokens |
| Python Library | Simplifies HTTP requests | requests |
APIs are the glue of modern applications β once you understand how to call and handle them, you can connect to nearly any service or dataset on the internet.