Chapter 20: Quiz

Working with External APIs and Integrations

Test your understanding of external API integration concepts, patterns, and best practices.


Question 1

Which Python HTTP library supports both synchronous and asynchronous requests natively?

  • A) requests
  • B) urllib3
  • C) httpx
  • D) aiohttp
Answer **C) `httpx`** `httpx` provides both `httpx.Client` (synchronous) and `httpx.AsyncClient` (asynchronous) with a unified API. `requests` is synchronous only, `aiohttp` is asynchronous only, and `urllib3` is a lower-level library used by `requests` internally.

Question 2

In the OAuth 2.0 Authorization Code flow, what is exchanged for an access token?

  • A) The user's username and password
  • B) The client secret alone
  • C) An authorization code received via redirect
  • D) A refresh token
Answer **C) An authorization code received via redirect** In the Authorization Code flow, the user is redirected to the authorization server, logs in, and is redirected back to the application with an authorization code. The application's server then exchanges this code (along with the client ID and secret) for an access token. This ensures the access token is never exposed to the user's browser.

Question 3

What is the primary purpose of an idempotency key in payment processing?

  • A) To encrypt the payment data in transit
  • B) To ensure a payment operation is only performed once, even if the request is retried
  • C) To authenticate the payment request with the processor
  • D) To track the payment in the application's database
Answer **B) To ensure a payment operation is only performed once, even if the request is retried** If a network error occurs during a payment request and the client retries, the idempotency key tells the payment processor that this is a retry of the same operation, not a new payment. Without it, the customer could be charged multiple times.

Question 4

Which OAuth 2.0 grant type is most appropriate for a backend service that needs to access an API without any user involvement?

  • A) Authorization Code
  • B) Authorization Code with PKCE
  • C) Client Credentials
  • D) Device Code
Answer **C) Client Credentials** The Client Credentials grant is designed for server-to-server communication where no user context is needed. The application authenticates directly with its client ID and client secret to obtain an access token. Authorization Code flows require user interaction, and Device Code is for devices with limited input capabilities.

Question 5

What should your webhook endpoint do FIRST when it receives a request?

  • A) Parse the JSON body
  • B) Verify the webhook signature
  • C) Process the event
  • D) Return a 200 response
Answer **B) Verify the webhook signature** Before processing any webhook payload, you must verify the cryptographic signature to ensure the request came from the expected service and was not tampered with. Processing unsigned webhooks opens your application to spoofed events from malicious actors.

Question 6

In exponential backoff with jitter, what is the purpose of the jitter component?

  • A) To make the delay more predictable
  • B) To reduce the total retry time
  • C) To prevent multiple clients from retrying at the same time (thundering herd)
  • D) To increase the delay between retries
Answer **C) To prevent multiple clients from retrying at the same time (thundering herd)** Without jitter, if many clients fail at the same time, they will all retry at exactly the same intervals (1s, 2s, 4s...), potentially overwhelming the recovering service. Jitter adds random variation so retries are spread out over time.

Question 7

What are the three states of a circuit breaker, in order from normal operation to failure?

  • A) Open, Closed, Half-Open
  • B) Closed, Open, Half-Open
  • C) Active, Inactive, Testing
  • D) Green, Red, Yellow
Answer **B) Closed, Open, Half-Open** Closed = normal operation (requests pass through). Open = failure detected (requests are immediately rejected). Half-Open = testing recovery (limited requests allowed). The naming is counterintuitive because it comes from electrical circuit terminology: a closed circuit allows current to flow.

Question 8

When a circuit breaker is in the OPEN state, what happens to incoming requests?

  • A) They are queued for later processing
  • B) They are immediately rejected without calling the external service
  • C) They are retried with exponential backoff
  • D) They are routed to a backup service automatically
Answer **B) They are immediately rejected without calling the external service** When the circuit is open, the breaker immediately fails requests without making the external call. This protects both your application (avoiding timeouts) and the external service (avoiding additional load on an already struggling system). After a recovery timeout period, the circuit transitions to Half-Open to test if the service has recovered.

Question 9

What is the recommended way to handle file uploads to cloud storage in a web application?

  • A) Upload files through your server and forward them to cloud storage
  • B) Generate a pre-signed URL and have the client upload directly to cloud storage
  • C) Store files on your server's local disk and sync them to cloud storage nightly
  • D) Embed cloud storage credentials in the client-side code
Answer **B) Generate a pre-signed URL and have the client upload directly to cloud storage** Pre-signed URLs allow the client to upload directly to cloud storage without the file passing through your server. This reduces your server's bandwidth and processing load. The URL is time-limited and scoped to a specific operation, so it does not expose your storage credentials.

Question 10

Which HTTP status code indicates that you have exceeded an API's rate limit?

  • A) 401 Unauthorized
  • B) 403 Forbidden
  • C) 429 Too Many Requests
  • D) 503 Service Unavailable
Answer **C) 429 Too Many Requests** HTTP 429 specifically indicates rate limiting. It is often accompanied by a `Retry-After` header telling the client how long to wait. 401 is for authentication failures, 403 is for authorization failures, and 503 is for general server unavailability.

Question 11

Why should webhook handlers be idempotent?

  • A) To improve performance
  • B) Because webhook providers may send the same event multiple times
  • C) To comply with HTTP standards
  • D) To reduce network traffic
Answer **B) Because webhook providers may send the same event multiple times** Webhook providers retry delivery when they do not receive a timely response (due to network issues, server errors, etc.). Your handler may receive the same event 2-5 times. If the handler is not idempotent, it might process the same payment twice or send duplicate emails.

Question 12

What is the Strategy Pattern as applied to notification services in this chapter?

  • A) A pattern for choosing the best notification time
  • B) Defining a common interface for notification channels and swapping implementations
  • C) A pattern for prioritizing notifications by urgency
  • D) A retry strategy specific to notification delivery
Answer **B) Defining a common interface for notification channels and swapping implementations** The Strategy Pattern defines a family of algorithms (notification channels like email, SMS, Slack), encapsulates each one behind a common interface (`NotificationChannel`), and makes them interchangeable. This allows adding new channels without modifying the core notification logic.

Question 13

When consuming a REST API, why should you always set explicit timeouts?

  • A) To improve API response times
  • B) To prevent a hung external service from blocking your entire application
  • C) To comply with the API's terms of service
  • D) To reduce the number of retry attempts
Answer **B) To prevent a hung external service from blocking your entire application** Without timeouts, if an external service stops responding, your HTTP client will wait indefinitely, tying up resources (threads, connections, memory). In a web application, this can cascade into all request handlers being blocked, effectively taking down your entire service.

Question 14

What is tokenization in the context of payment processing?

  • A) Splitting payment data into smaller chunks for parallel processing
  • B) Replacing sensitive card data with a non-sensitive placeholder token
  • C) Encrypting payment data with a rotating key
  • D) Converting payment amounts to a different currency
Answer **B) Replacing sensitive card data with a non-sensitive placeholder token** Tokenization means the customer's actual card number never touches your server. The card details go directly to the payment processor (via a client-side widget), and your server only receives a token that represents the payment method. This dramatically reduces your PCI compliance burden.

Question 15

What does asyncio.gather() do when used with multiple API calls?

  • A) Executes API calls sequentially and returns the first successful result
  • B) Executes API calls concurrently and returns all results when complete
  • C) Executes API calls in parallel threads
  • D) Cancels all API calls if any one fails
Answer **B) Executes API calls concurrently and returns all results when complete** `asyncio.gather()` runs multiple coroutines concurrently (not in parallel threads -- it uses cooperative multitasking on a single thread). It waits for all coroutines to complete and returns their results as a list. With `return_exceptions=True`, it captures exceptions instead of raising them, which is useful for best-effort processing.

Question 16

Which of the following is NOT a reason to use an abstraction layer over a direct API integration?

  • A) Ability to swap providers without changing application code
  • B) Improved performance through caching
  • C) Automatic access to the latest API features
  • D) Simplified testing through interface mocking
Answer **C) Automatic access to the latest API features** Abstraction layers actually make it *harder* to access provider-specific features because they work through a common interface. The other options are genuine benefits: abstraction allows provider swapping, caching can be built into the abstraction, and testing is simplified because you can mock the abstract interface rather than the specific API.

Question 17

When using the Retry-After header from a 429 response, what should your client do?

  • A) Ignore it and retry immediately
  • B) Wait for the specified duration before making another request
  • C) Reduce the request payload size
  • D) Switch to a different API endpoint
Answer **B) Wait for the specified duration before making another request** The `Retry-After` header tells the client exactly how long to wait (in seconds or as a date) before the rate limit resets. Respecting this header is more efficient than generic exponential backoff because it tells you precisely when you can resume.

Question 18

In the event-driven webhook processing model, why is it important to return a 200 response quickly?

  • A) To improve your application's SEO
  • B) Because webhook providers interpret slow responses as failures and will retry
  • C) To reduce bandwidth usage
  • D) Because HTTP connections automatically close after 1 second
Answer **B) Because webhook providers interpret slow responses as failures and will retry** Most webhook providers have a timeout (typically 5-30 seconds). If your endpoint does not respond in time, the provider considers the delivery failed and will retry. If your processing takes longer, acknowledge receipt with a 200 response immediately and process the event asynchronously.

Question 19

What is the purpose of the state parameter in an OAuth 2.0 authorization request?

  • A) To store the user's session data
  • B) To prevent Cross-Site Request Forgery (CSRF) attacks
  • C) To specify the OAuth scopes requested
  • D) To cache the authorization response
Answer **B) To prevent Cross-Site Request Forgery (CSRF) attacks** The `state` parameter is a random, unguessable value generated by the client. It is sent with the authorization request and returned in the callback. The client verifies that the returned state matches, ensuring the callback was triggered by a legitimate authorization request and not a CSRF attack.

Question 20

When should you use the Client Credentials OAuth flow instead of the Authorization Code flow?

  • A) When the application needs to act on behalf of a specific user
  • B) When the application is a single-page app running in the browser
  • C) When the application needs to access its own resources or service-level data without user context
  • D) When the application needs offline access to user data
Answer **C) When the application needs to access its own resources or service-level data without user context** Client Credentials is a machine-to-machine flow. There is no user involved -- the application authenticates as itself. Use cases include accessing service-level APIs, background job processing, and inter-service communication in a microservices architecture.

Question 21

What is the "best effort" pattern in multi-service integration?

  • A) Trying each service once and accepting any failures
  • B) Running all service calls concurrently and continuing even if some fail
  • C) Only using the fastest responding service
  • D) Retrying all failed services indefinitely
Answer **B) Running all service calls concurrently and continuing even if some fail** The best-effort pattern (using `asyncio.gather(return_exceptions=True)`) runs all integration calls concurrently. Individual failures are logged and tracked but do not prevent other services from completing. This ensures that a Slack notification failure, for example, does not prevent a confirmation email from being sent.

Question 22

Why should you validate external API responses with Pydantic models?

  • A) To improve network performance
  • B) To ensure the response data matches expected types and structure before your code processes it
  • C) To compress the response data
  • D) To encrypt the response data at rest
Answer **B) To ensure the response data matches expected types and structure before your code processes it** External APIs can change their response format, return unexpected null values, or include additional fields. Pydantic validation catches these issues at the boundary, producing clear error messages instead of mysterious failures deep in your business logic.

Question 23

What is a token bucket rate limiter?

  • A) A system that stores API tokens in a bucket data structure
  • B) An algorithm that allows a configurable burst of requests up to a maximum, then throttles to a steady rate
  • C) A method for distributing API keys to multiple clients
  • D) A way to compress multiple API requests into a single call
Answer **B) An algorithm that allows a configurable burst of requests up to a maximum, then throttles to a steady rate** The token bucket starts full (allowing burst traffic). Each request removes a token. Tokens refill at a steady rate. When empty, requests must wait for tokens to refill. This allows short bursts of activity while enforcing an average rate limit over time.

Question 24

Which of the following is the MOST important security practice when handling payment webhooks?

  • A) Using HTTPS for the webhook URL
  • B) Verifying the webhook signature before processing the payload
  • C) Logging the full webhook payload
  • D) Responding within 5 seconds
Answer **B) Verifying the webhook signature before processing the payload** While all options are good practices, signature verification is the most critical security measure. Without it, anyone who discovers your webhook URL could send fake payment events, potentially triggering fraudulent order fulfillment. HMAC signature verification cryptographically proves the webhook came from the expected payment processor.

Question 25

In the context of graceful degradation, what should your application do when an external weather API is unavailable?

  • A) Crash and display an error page to the user
  • B) Return the last known cached data (marked as stale) or a meaningful fallback
  • C) Keep retrying the API call until it succeeds
  • D) Redirect the user to the weather API's website
Answer **B) Return the last known cached data (marked as stale) or a meaningful fallback** Graceful degradation means providing a reduced but functional experience when dependencies fail. For non-critical services like weather data, returning stale cached data (clearly marked as such) is far better than failing the entire request. For critical services with no fallback, a clear error message is appropriate.

Scoring Guide

Score Level Recommendation
23-25 Expert You have a strong grasp of API integration patterns. Proceed to advanced exercises.
18-22 Proficient Good understanding with some gaps. Review the sections for questions you missed.
13-17 Developing Solid foundation but needs reinforcement. Re-read the chapter and attempt Tier 1-2 exercises.
8-12 Beginning Review the chapter thoroughly, focusing on sections 20.2, 20.3, and 20.9.
0-7 Needs Review Start with the chapter introduction and work through each section with the code examples.