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:

That’s exactly how applications communicate β€” through structured requests and responses.


🧠 2. Why APIs Matter

BenefitDescription
ModularityAllows applications to use external services (e.g., Google Maps API).
IntegrationEnables different systems to share data and functionality.
AutomationPowers bots, data pipelines, and cloud orchestration.
ScalabilityLets 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

TypeDescriptionExample
Public APIOpen to everyone with documentationOpenWeatherMap, NASA API
Private APIUsed internally by organizationsCompany microservices
Partner APIShared with selected partnersPayment gateway APIs
REST APIUses HTTP methods to access dataGET /users, POST /orders
GraphQL APIQuery language for APIsFacebook GraphQL
WebSocket APIEnables real-time communicationChat, stock updates

🧱 4. Anatomy of an API Request

Most APIs use HTTP β€” the same protocol your browser uses.

PartExampleDescription
Endpoint (URL)https://api.example.com/usersAPI address
MethodGET, POST, PUT, DELETEType of action
HeadersAuthorization: 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 CodeMeaning
200Success
201Created
400Bad request
401Unauthorized
404Not found
500Server 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

FeatureRESTGraphQLWebSocket
StructureMultiple endpointsSingle endpoint with queriesPersistent connection
DataFixed responsesFlexible queriesContinuous updates
Use CaseCRUD APIsData-heavy appsReal-time data

🧰 12. Testing and Debugging APIs

ToolUse
PostmanVisual API testing and documentation
curlCommand-line API testing
HTTPieSimple 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

ConceptDescriptionExample
APIInterface that connects software systemsREST, GraphQL
HTTP MethodsDefine actions to performGET, POST, PUT, DELETE
Response CodesIndicate success or failure200, 404, 500
AuthenticationProtects accessAPI keys, tokens
Python LibrarySimplifies HTTP requestsrequests

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.