Module 4 - Understanding and Using APIs
Module 4 - Understanding and Using APIs
Brief Overview
This note covers APIs and was created from a 85-page PDF. It provides a deep dive into API fundamentals, design
styles, REST mechanics, authentication, rate limits, and webhook basics.
Key Points
Understand the difference between synchronous and asynchronous APIs and when to use each.
Learn the core architectural styles (RPC, SOAP, REST) and their typical protocols.
Get practical guidance on authenticating to REST APIs (Basic, Bearer, API Key, OAuth).
📚 Introducing APIs
API – An Application Programming Interface allows one piece of software to talk to another, exposing data, services,
and functionality in a controlled, secure way.
Uses
Automation – scripts replace manual tasks.
Data integration – consume/react to external data.
Functionality extension – embed another app’s features.
Popularity drivers
Built‑in to modern products, thoroughly tested.
Simplified languages (e.g., Python) let non‑engineers build API clients.
Shows a layered architecture with load balancer, authentication, books, and orders services.
Request Components
1. Uniform Resource Identifier (URI) – locates the target resource.
Scheme (http/https)
Authority (host:port)
Path (/v1/books/)
Query (?q=DevNet)
Visual split of a URL into scheme, authority, path, and query.
2. HTTP Method – defines the action.
Method Action Description
POST Create New object/resource.
GET Read Retrieve resource details.
PUT Update Replace existing resource.
PATCH Partial Update Modify part of a resource.
DELETE Delete Remove a resource.
3. Headers – name‑value pairs.
Request headers (e.g., Authorization: Basic …) convey metadata.
Entity headers (e.g., Content-Type: application/json) describe the body.
4. Body – optional payload for POST, PUT, PATCH; format indicated by Content-Type.
Response Components
HTTP Status – three‑digit code indicating outcome (e.g., 200 OK, 404 Not Found).
Headers – response and entity metadata (e.g., Set-Cookie, Cache‑Control).
Body – optional data payload.
Common status codes
Code Message Meaning
200 OK Success; usually includes a body.
201 Created Resource successfully created.
202 Accepted Request accepted, processing
pending.
400 Bad Request Client error – malformed request.
401 Unauthorized Missing/invalid authentication.
403 Forbidden Authenticated but not allowed.
404 Not Found Resource does not exist.
500 Internal Server Error Server failure.
503 Service Unavailable Server overloaded or down.
🛡️ Authorization – OAuth
OAuth 2.0 (not backward compatible with 1.0) enables third‑party apps to obtain limited access via an access
token.
Flow – user authenticates to an Identity Provider, receives token, presents token to API.
Shows water (requests) filling a glass (queue) inconsistently while draining at a constant rate.
🛠️ Practical Tools
cURL (Command‑line)
Postman
GUI platform for building, testing, and documenting APIs.
Supports collections, environments, automated testing, and collaboration workspaces.
name = "ABC"
age = 55
f"Hello {name}, you are {age}"
# → 'Hello ABC, you are 55'
Token Bucket
A bucket holds a certain number of tokens. One token is consumed per request; tokens are replenished at a fixed
rate.
How it works
1. The server adds X tokens to the bucket every time interval (e.g., 2 tokens / minute).
2. When a client sends a request, the server checks for at least one token.
3. If a token exists, it is removed and the request is processed; otherwise the request is rejected.
Client responsibility – calculate the current token count to avoid unnecessary rejections.
The diagram shows tokens flowing into a bucket and being taken out for each request, visualising the “add‑X‑tokens,
remove‑one‑per‑request” cycle.
Fixed Window Counter
A counter tracks the number of requests that have occurred within a static time window (e.g., each minute).
The counter starts at zero at the beginning of the window.
Each processed request increments the counter.
Once the limit for that window is reached, all subsequent requests in the same window are rejected.
No token accumulation – counters reset only when the next window begins.
Client must know the exact start/end of the window to track usage.
Green squares = accepted requests; red squares = rejected requests across successive one‑minute windows.
Sliding Window Counter
Combines the simplicity of a fixed window with finer granularity by counting requests in the rolling interval preceding
the current moment.
When a request arrives, the server counts all requests that occurred in the past T seconds (or minutes).
If the count is below the limit, the request proceeds; otherwise it is rejected.
This approach smooths spikes that would otherwise be penalized by a hard reset in the fixed‑window model.
Quick Comparison
Algorithm Token accumulation Window type Typical use case
Token Bucket Yes (tokens stored) Continuous (replenish rate) Burst‑friendly traffic (e.g.,
API bursts)
Fixed Window No Rigid, discrete Simple quotas (e.g., “10
requests per minute”)
Sliding Window No Rolling Fairness across sliding
intervals, avoiding burst
penalties
Header Meaning
X-RateLimit-Limit Maximum allowed requests per time unit
X-RateLimit-Remaining Requests left in the current window
X-RateLimit-Reset Epoch time when the window resets (or seconds until
reset)
These headers let a client self‑throttle and avoid 429 errors.
1. Gather Essentials
API reference (endpoint definitions, required headers).
Authentication details (API key, token, username/password).
Class Description
1xx Informational
2xx Success (e.g., 200 OK, 201 Created)
3xx Redirection
4xx Client error (invalid request, auth, etc.)
5xx Server error (faulty backend, overload)
response = [Link](url)
print(response.status_code, [Link])
4. Diagnostic Tips
Print the status code and response body during development.
Use tools like curl -v or Postman’s “Console” to view raw headers.
For server‑side failures, capture network traffic (Wireshark) or request server logs if you have access.
Proxy authentication (407) requires credentials for the intermediate proxy before reaching the target API.
# Simple Python GET with disabled SSL verification (use only for testing)
import requests
url = "[Link]
resp = [Link](url, verify=False, auth=("user","pass"))
print(resp.status_code, [Link])
These snippets illustrate how to inspect responses and toggle verification when dealing with self‑signed certificates in
lab environments.
Key Points
Understand the difference between synchronous and asynchronous APIs and when to use each.
Learn the core architectural styles (RPC, SOAP, REST) and their typical protocols.
Get practical guidance on authenticating to REST APIs (Basic, Bearer, API Key, OAuth).
📚 Introducing APIs
API – An Application Programming Interface allows one piece of software to talk to another, exposing data, services,
and functionality in a controlled, secure way.
Uses
Automation – scripts replace manual tasks.
Data integration – consume/react to external data.
Functionality extension – embed another app’s features.
Popularity drivers
Built‑in to modern products, thoroughly tested.
Simplified languages (e.g., Python) let non‑engineers build API clients.
The image shows customers waiting in line, illustrating the blocking nature of synchronous calls.
⏱️ Asynchronous APIs
Acknowledge receipt of the request without returning data; processing happens later.
Shows a layered architecture with load balancer, authentication, books, and orders services.
Request Components
1. Uniform Resource Identifier (URI) – locates the target resource.
Scheme (http/https)
Authority (host:port)
Path (/v1/books/)
Query (?q=DevNet)
Shows water (requests) filling a glass (queue) inconsistently while draining at a constant rate.
🛠️ Practical Tools
cURL (Command‑line)
Postman
GUI platform for building, testing, and documenting APIs.
Supports collections, environments, automated testing, and collaboration workspaces.
name = "ABC"
age = 55
f"Hello {name}, you are {age}"
# → 'Hello ABC, you are 55'
Token Bucket
A bucket holds a certain number of tokens. One token is consumed per request; tokens are replenished at a fixed
rate.
How it works
1. The server adds X tokens to the bucket every time interval (e.g., 2 tokens / minute).
2. When a client sends a request, the server checks for at least one token.
3. If a token exists, it is removed and the request is processed; otherwise the request is rejected.
Client responsibility – calculate the current token count to avoid unnecessary rejections.
The diagram shows tokens flowing into a bucket and being taken out for each request, visualising the “add‑X‑tokens,
remove‑one‑per‑request” cycle.
Fixed Window Counter
A counter tracks the number of requests that have occurred within a static time window (e.g., each minute).
Green squares = accepted requests; red squares = rejected requests across successive one‑minute windows.
Sliding Window Counter
Combines the simplicity of a fixed window with finer granularity by counting requests in the rolling interval preceding
the current moment.
When a request arrives, the server counts all requests that occurred in the past T seconds (or minutes).
If the count is below the limit, the request proceeds; otherwise it is rejected.
This approach smooths spikes that would otherwise be penalized by a hard reset in the fixed‑window model.
Quick Comparison
Algorithm Token accumulation Window type Typical use case
Token Bucket Yes (tokens stored) Continuous (replenish rate) Burst‑friendly traffic (e.g.,
API bursts)
Fixed Window No Rigid, discrete Simple quotas (e.g., “10
requests per minute”)
Sliding Window No Rolling Fairness across sliding
intervals, avoiding burst
penalties
Header Meaning
X-RateLimit-Limit Maximum allowed requests per time unit
X-RateLimit-Remaining Requests left in the current window
X-RateLimit-Reset Epoch time when the window resets (or seconds until
reset)
These headers let a client self‑throttle and avoid 429 errors.
1. Gather Essentials
API reference (endpoint definitions, required headers).
Authentication details (API key, token, username/password).
Class Description
1xx Informational
2xx Success (e.g., 200 OK, 201 Created)
3xx Redirection
4xx Client error (invalid request, auth, etc.)
5xx Server error (faulty backend, overload)
response = [Link](url)
print(response.status_code, [Link])
4. Diagnostic Tips
Print the status code and response body during development.
Use tools like curl -v or Postman’s “Console” to view raw headers.
For server‑side failures, capture network traffic (Wireshark) or request server logs if you have access.
Proxy authentication (407) requires credentials for the intermediate proxy before reaching the target API.
# Simple Python GET with disabled SSL verification (use only for testing)
import requests
url = "[Link]
resp = [Link](url, verify=False, auth=("user","pass"))
print(resp.status_code, [Link])
These snippets illustrate how to inspect responses and toggle verification when dealing with self‑signed certificates in
lab environments.