Working with APIs — What Are APIs?

Published: November 12, 2025 • Language: python • Chapter: 11 • Sub: 1 • Level: beginner

python

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=payload instead of data=payload to 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.