0% found this document useful (0 votes)
5 views23 pages

Module 4 - Understanding and Using APIs

This document provides an in-depth overview of API design essentials, covering key topics such as API fundamentals, design styles (RPC, SOAP, REST), authentication methods, rate limits, and webhooks. It explains the differences between synchronous and asynchronous APIs, details the request/response model for REST APIs, and outlines various authentication mechanisms including OAuth. Additionally, it discusses practical tools for API testing and troubleshooting techniques for common issues.

Uploaded by

xiaotianxinzz
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views23 pages

Module 4 - Understanding and Using APIs

This document provides an in-depth overview of API design essentials, covering key topics such as API fundamentals, design styles (RPC, SOAP, REST), authentication methods, rate limits, and webhooks. It explains the differences between synchronous and asynchronous APIs, details the request/response model for REST APIs, and outlines various authentication mechanisms including OAuth. Additionally, it discusses practical tools for API testing and troubleshooting techniques for common issues.

Uploaded by

xiaotianxinzz
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

📚 API Design Essentials

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.

⚡ API Design Styles


🔄 Synchronous APIs
Respond immediately with data when the request can be fulfilled instantly.
When to use – data is readily available.
Benefits – immediate response, potentially better performance if designed well.
Client behavior – must wait for the response before continuing.

Example: Ticket sales at a box office are processed first‑come, first‑served.


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.
When to use – operations take time or data isn’t immediately available.
Benefits – client can continue execution, improving overall performance.
Client behavior – handles a “request received” response and processes the final result later.

🏛️ API Architectural Styles


Style Core Idea Typical Protocols
RPC Request‑response remote procedure XML‑RPC, JSON‑RPC, NFS
calls
SOAP XML‑based messaging across HTTP, SMTP, TCP, UDP, JMS
platforms
REST Resource‑oriented, stateless HTTP
interactions

📡 Remote Procedure Call (RPC)


Client calls a procedure on a server; the server executes and returns the result.
Flowchart visualizing the request‑response cycle of RPC.
📧 Simple Object Access Protocol (SOAP)
XML‑based messaging, independent of platform.
Extensible (adds reliability, security).
Neutral – works over any transport (HTTP, SMTP, etc.).
SOAP message structure
1. Envelope – root element.
2. Header – metadata (e.g., authorization).
3. Body – payload.
4. Fault – error/status info.
🌐 REpresentational State Transfer (REST)
Authored by Roy Thomas Fielding; defined by six constraints:
Constraint Description
Client‑server Independent development of client and server.
Stateless Each request contains all information needed; no session
state on server.
Cacheable Responses indicate cacheability; cached data can be
reused.
Uniform interface Four principles: resource identification, manipulation via
representations, self‑descriptive messages, hypermedia
as engine of application state.
Layered system Hierarchical layers; each layer only sees the one directly
above/below it.
Code‑on‑demand (optional) Server can return executable code (e.g., JavaScript) to
extend client functionality.
Illustrates the client‑server interaction, including a cache layer.

Shows a layered architecture with load balancer, authentication, books, and orders services.

🛰️ Introduction to REST APIs


📡 Request/Response Model
REST APIs communicate over HTTP, using standard verbs, status codes, headers, and optional bodies.

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.

Additional Response Features


Pagination – split large result sets using query parameters (e.g., page=2).
Compressed data – request with Accept‑Encoding: gzip (or deflate, br, etc.) to reduce payload size.
Sequence Diagrams (API workflow)
1. Create session – HTTPS POST with credentials.
2. Get devices – Retrieve list via GET.
3. Create device – POST new device definition.

🔐 Authenticating to a REST API


🔑 Authentication vs. Authorization
Authentication – verifies who you are (e.g., ID check).
Authorization – determines what you are allowed to do (e.g., ticket to a concert).

Illustrates authentication (ID) and authorization (ticket).


🔐 Authentication Mechanisms
Mechanism How it works Security notes
Basic Authorization: Basic Insecure unless combined with
HTTPS.
Bearer Authorization: Bearer Token issued by an IdP; common with
OAuth/SSO.
API Key Sent via header, query string, body, Secure only over HTTPS; key is
or cookie (Authorization: ). static.

🛡️ 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.

⏱️ API Rate Limits


What are Rate Limits?
Controls the number of requests a client can make per time unit, preventing overload and mitigating DoS attacks.
Leaky Bucket Algorithm
Requests enter a queue in arrival order.
Server processes at a fixed rate; excess requests are dropped if the queue is full.

Shows water (requests) filling a glass (queue) inconsistently while draining at a constant rate.

🛠️ Practical Tools
cURL (Command‑line)

curl -X POST "[Link] \


-H "accept: application/json" \
-H "X-API-KEY: cisco|-6R9DWt3K_frdBMM3XYtHicMqgO9tSEJcf8NQgD0kq0" \
-H "Content-Type: application/json" \
-d '{ "id": 4, "title": "IPv6 Fundamentals", "author": "Rick Graziani"}'

-X specifies HTTP method.


-H adds headers.
-d provides request body.
Sample GET with query parameters

curl -X GET "[Link] \


-H "accept: application/json"

Obtain token (Basic auth)

curl -X POST "[Link] \


-H "accept: application/json" \
-u "cisco:Cisco123!"

Postman
GUI platform for building, testing, and documenting APIs.
Supports collections, environments, automated testing, and collaboration workspaces.

Shows the request builder, headers, and response panels.


Python f‑Strings (used in lab scripts)

name = "ABC"
age = 55
f"Hello {name}, you are {age}"
# → 'Hello ABC, you are 55'

Convenient for constructing URLs, JSON payloads, and logging messages.

⏲️ Rate‑Limit Algorithms (continued) 🚦


Rate‑limit algorithms decide how and when a request is allowed based on a predefined quota.

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

📊 Knowing the Rate Limit 📈


Many APIs expose their quota details in HTTP response headers.

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.

🚫 Exceeding the Rate Limit ❗


The server returns an error response immediately when the quota is surpassed.
Common status codes:
429 Too Many Requests – standard “rate limit exceeded” response.
403 Forbidden – sometimes used when the client is explicitly blocked.

📢 Working with Webhooks – Reverse APIs 🔄


A webhook is an HTTP POST sent by a provider to a consumer‑registered URL whenever a specific event occurs.
Eliminates the need for polling (periodic GET requests).
Multiple consumers can subscribe to the same webhook source.
Typical use cases:
Cisco DNA Center pushes network‑event data to a monitoring app.
Cisco Webex Teams notifies a bot when a new message appears in a room.
Consuming a Webhook ✅
1. Run a server that can accept incoming POSTs at all times.
2. Register the server’s URI with the webhook provider.
3. Handle the JSON payload (verify signatures, parse data, respond with 200 OK).
4. Use online services (e.g., [Link], requestbin) to debug incoming calls during development.

🐞 Troubleshooting API Calls 🔎


When a request does not behave as expected, follow a systematic diagnostic path.

1. Gather Essentials
API reference (endpoint definitions, required headers).
Authentication details (API key, token, username/password).

2. No Response / Missing Status Code


Possible cause Check Typical symptom
Invalid URI Verify scheme (http/https) and [Link]
spelling
Wrong domain Ping the host or browse the URL DNS‑resolution error
Connectivity Inspect proxy, firewall, VPN settings ConnectionError / timeout
SSL certificate Use verify=False in Python for testing SSLError during handshake

Traceback shows a failure to establish a new connection – typical of network‑level problems.


3. Interpreting HTTP Status Codes
The first digit categorises the response.

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)

Common 4xx Errors


400 Bad Request – malformed JSON, missing required fields.
Example: "No id field provided" when id is mandatory.

response = [Link](url)
print(response.status_code, [Link])

401 Unauthorized – credentials missing or wrong.


403 Forbidden – authenticated but lacks required permissions.
409 Conflict – resource state conflict (e.g., concurrent edits).
415 Unsupported Media Type – sending XML to a JSON‑only endpoint; fix by setting Content-Type:
application/json.
Common 5xx Errors
Code Meaning
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable (overload/maintenance)
504 Gateway Timeout

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.

📄 Sample Code Snippets (reference)


# GET with query parameters (cURL)
curl -X GET "[Link] \
-H "accept: application/json"

# 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.

📚 API Design Essentials


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.

⚡ API Design Styles


🔄 Synchronous APIs
Respond immediately with data when the request can be fulfilled instantly.

When to use – data is readily available.


Benefits – immediate response, potentially better performance if designed well.
Client behavior – must wait for the response before continuing.

Example: Ticket sales at a box office are processed first‑come, first‑served.

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.

When to use – operations take time or data isn’t immediately available.


Benefits – client can continue execution, improving overall performance.
Client behavior – handles a “request received” response and processes the final result later.
🏛️ API Architectural Styles
Style Core Idea Typical Protocols
RPC Request‑response remote procedure XML‑RPC, JSON‑RPC, NFS
calls
SOAP XML‑based messaging across HTTP, SMTP, TCP, UDP, JMS
platforms
REST Resource‑oriented, stateless HTTP
interactions

📡 Remote Procedure Call (RPC)


Client calls a procedure on a server; the server executes and returns the result.

Flowchart visualizing the request‑response cycle of RPC.


📧 Simple Object Access Protocol (SOAP)
XML‑based messaging, independent of platform.
Extensible (adds reliability, security).
Neutral – works over any transport (HTTP, SMTP, etc.).
SOAP message structure
1. Envelope – root element.
2. Header – metadata (e.g., authorization).
3. Body – payload.
4. Fault – error/status info.
🌐 REpresentational State Transfer (REST)
Authored by Roy Thomas Fielding; defined by six constraints:
Constraint Description
Client‑server Independent development of client and server.
Stateless Each request contains all information needed; no session
state on server.
Cacheable Responses indicate cacheability; cached data can be
reused.
Uniform interface Four principles: resource identification, manipulation via
representations, self‑descriptive messages, hypermedia
as engine of application state.
Layered system Hierarchical layers; each layer only sees the one directly
above/below it.
Code‑on‑demand (optional) Server can return executable code (e.g., JavaScript) to
extend client functionality.

Illustrates the client‑server interaction, including a cache layer.

Shows a layered architecture with load balancer, authentication, books, and orders services.

🛰️ Introduction to REST APIs


📡 Request/Response Model
REST APIs communicate over HTTP, using standard verbs, status codes, headers, and optional bodies.

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.
Additional Response Features
Pagination – split large result sets using query parameters (e.g., page=2).
Compressed data – request with Accept‑Encoding: gzip (or deflate, br, etc.) to reduce payload size.
Sequence Diagrams (API workflow)
1. Create session – HTTPS POST with credentials.
2. Get devices – Retrieve list via GET.
3. Create device – POST new device definition.

🔐 Authenticating to a REST API


🔑 Authentication vs. Authorization
Authentication – verifies who you are (e.g., ID check).
Authorization – determines what you are allowed to do (e.g., ticket to a concert).

Illustrates authentication (ID) and authorization (ticket).


🔐 Authentication Mechanisms
Mechanism How it works Security notes
Basic Authorization: Basic Insecure unless combined with
HTTPS.
Bearer Authorization: Bearer Token issued by an IdP; common with
OAuth/SSO.
API Key Sent via header, query string, body, Secure only over HTTPS; key is
or cookie (Authorization: ). static.
🛡️ 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.

⏱️ API Rate Limits


What are Rate Limits?
Controls the number of requests a client can make per time unit, preventing overload and mitigating DoS attacks.

Leaky Bucket Algorithm


Requests enter a queue in arrival order.
Server processes at a fixed rate; excess requests are dropped if the queue is full.

Shows water (requests) filling a glass (queue) inconsistently while draining at a constant rate.

🛠️ Practical Tools
cURL (Command‑line)

curl -X POST "[Link] \


-H "accept: application/json" \
-H "X-API-KEY: cisco|-6R9DWt3K_frdBMM3XYtHicMqgO9tSEJcf8NQgD0kq0" \
-H "Content-Type: application/json" \
-d '{ "id": 4, "title": "IPv6 Fundamentals", "author": "Rick Graziani"}'

-X specifies HTTP method.


-H adds headers.
-d provides request body.
Sample GET with query parameters

curl -X GET "[Link] \


-H "accept: application/json"

Obtain token (Basic auth)

curl -X POST "[Link] \


-H "accept: application/json" \
-u "cisco:Cisco123!"

Postman
GUI platform for building, testing, and documenting APIs.
Supports collections, environments, automated testing, and collaboration workspaces.

Shows the request builder, headers, and response panels.


Python f‑Strings (used in lab scripts)

name = "ABC"
age = 55
f"Hello {name}, you are {age}"
# → 'Hello ABC, you are 55'

Convenient for constructing URLs, JSON payloads, and logging messages.

⏲️ Rate‑Limit Algorithms (continued) 🚦


Rate‑limit algorithms decide how and when a request is allowed based on a predefined quota.

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

📊 Knowing the Rate Limit 📈


Many APIs expose their quota details in HTTP response headers.

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.

🚫 Exceeding the Rate Limit ❗


The server returns an error response immediately when the quota is surpassed.
Common status codes:
429 Too Many Requests – standard “rate limit exceeded” response.
403 Forbidden – sometimes used when the client is explicitly blocked.

📢 Working with Webhooks – Reverse APIs 🔄


A webhook is an HTTP POST sent by a provider to a consumer‑registered URL whenever a specific event occurs.

Eliminates the need for polling (periodic GET requests).


Multiple consumers can subscribe to the same webhook source.
Typical use cases:
Cisco DNA Center pushes network‑event data to a monitoring app.
Cisco Webex Teams notifies a bot when a new message appears in a room.
Consuming a Webhook ✅
1. Run a server that can accept incoming POSTs at all times.
2. Register the server’s URI with the webhook provider.
3. Handle the JSON payload (verify signatures, parse data, respond with 200 OK).
4. Use online services (e.g., [Link], requestbin) to debug incoming calls during development.
🐞 Troubleshooting API Calls 🔎
When a request does not behave as expected, follow a systematic diagnostic path.

1. Gather Essentials
API reference (endpoint definitions, required headers).
Authentication details (API key, token, username/password).

2. No Response / Missing Status Code


Possible cause Check Typical symptom
Invalid URI Verify scheme (http/https) and [Link]
spelling
Wrong domain Ping the host or browse the URL DNS‑resolution error
Connectivity Inspect proxy, firewall, VPN settings ConnectionError / timeout
SSL certificate Use verify=False in Python for testing SSLError during handshake

Traceback shows a failure to establish a new connection – typical of network‑level problems.


3. Interpreting HTTP Status Codes
The first digit categorises the response.

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)

Common 4xx Errors


400 Bad Request – malformed JSON, missing required fields.
Example: "No id field provided" when id is mandatory.

response = [Link](url)
print(response.status_code, [Link])

401 Unauthorized – credentials missing or wrong.


403 Forbidden – authenticated but lacks required permissions.
409 Conflict – resource state conflict (e.g., concurrent edits).
415 Unsupported Media Type – sending XML to a JSON‑only endpoint; fix by setting Content-Type:
application/json.
Common 5xx Errors
Code Meaning
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable (overload/maintenance)
504 Gateway Timeout

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.

📄 Sample Code Snippets (reference)


# GET with query parameters (cURL)
curl -X GET "[Link] \
-H "accept: application/json"

# 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.

You might also like