Ten questions at a time, drawn from 120. Every answer is explained. Nothing is saved and no account is needed.
An API consumer wants to update only the 'email' field of a user resource. Which method is most appropriate and semantically correct?
Practice quiz for REST API Design. Scores are not saved.
An API consumer wants to update only the 'email' field of a user resource. Which method is most appropriate and semantically correct?
Answer: PATCH. PATCH is designed for partial updates to a resource. PUT requires sending the entire resource, and GET/POST do not semantically represent partial modification or are not the most efficient choice for updates.
From lesson: HTTP Methods — GET, POST, PUT, PATCH, DELETE
Which HTTP method is required to be 'idempotent' but NOT 'safe'?
Answer: PUT. PUT is idempotent (multiple requests result in the same state) but unsafe (it changes state). GET is both safe and idempotent. POST is neither safe nor idempotent. DELETE is idempotent, but the question specifically targets the design property of PUT.
From lesson: HTTP Methods — GET, POST, PUT, PATCH, DELETE
If a server receives a request to a collection URL that creates a new resource, which status code is the standard best practice for a successful response?
Answer: 201 Created. 201 Created is the standard response for POST requests that successfully result in the creation of a new resource. 200 is too generic, 204 is for empty bodies, and 202 is for asynchronous processing.
From lesson: HTTP Methods — GET, POST, PUT, PATCH, DELETE
Why is it considered bad REST design to use GET for a request that deletes a record from the database?
Answer: GET requests should be safe and not cause side effects. GET is defined as a 'safe' method, meaning it should not change the state of the server. Using it to delete records violates this principle. Length limits and auth headers are implementation details, not REST design principles.
From lesson: HTTP Methods — GET, POST, PUT, PATCH, DELETE
A client sends a PUT request to update a user's address. If the request is successful but the client repeats the exact same request again, what should be the resulting state?
Answer: The resource should remain in the state it reached after the first request. Because PUT is idempotent, subsequent identical requests should not change the state beyond the initial modification. Options suggesting error-throwing, duplication, or deletion misinterpret the definition of idempotency.
From lesson: HTTP Methods — GET, POST, PUT, PATCH, DELETE
A client sends a POST request to create a new resource. The server successfully creates it, but the resource is processed asynchronously and isn't ready for retrieval yet. What is the most semantic status code?
Answer: 202 Accepted. 202 Accepted indicates the request is accepted for processing but not complete. 200 and 204 imply immediate completion, while 201 is for when the resource is immediately available at a specific URI.
From lesson: HTTP Status Codes — 2xx, 3xx, 4xx, 5xx
If a client provides an Authorization header with an expired token, which status code is most appropriate to signal that the client needs to re-authenticate?
Answer: 401 Unauthorized. 401 indicates that the request lacks valid authentication credentials. 403 is for when the user is known but lacks permissions, 400 is for malformed syntax, and 404 is for missing resources.
From lesson: HTTP Status Codes — 2xx, 3xx, 4xx, 5xx
An API consumer attempts to access a resource that they are authenticated for, but they lack the specific permissions to perform the requested action. What should the API return?
Answer: 403 Forbidden. 403 Forbidden signifies the server understood the request but refuses to authorize it. 401 is for missing credentials, 400 is for bad formatting, and 405 is for using the wrong HTTP verb (e.g., DELETE on a read-only endpoint).
From lesson: HTTP Status Codes — 2xx, 3xx, 4xx, 5xx
During a database migration, an API endpoint is temporarily unavailable. Which status code tells the client to try the request again later?
Answer: 503 Service Unavailable. 503 indicates temporary overloading or maintenance. 500 is a generic failure, 502 implies an issue between upstream servers, and 504 means the server didn't get a timely response from a backend dependency.
From lesson: HTTP Status Codes — 2xx, 3xx, 4xx, 5xx
A client performs a DELETE operation on a resource that has already been deleted. What is the most RESTful response if the requirement is to ensure the operation results in the resource being absent?
Answer: 204 No Content. 204 No Content is ideal for DELETE requests because the resource is confirmed to be absent, and no response body is needed. 404 and 410 indicate the resource doesn't exist, which can be confusing for an operation meant to ensure deletion. 200 requires a body response.
From lesson: HTTP Status Codes — 2xx, 3xx, 4xx, 5xx
A client sends a request to update a resource, but the server needs to ensure the resource hasn't changed since the client last fetched it. Which header is most appropriate for this task?
Answer: If-Match. If-Match is the standard header for conditional requests based on ETags, ensuring concurrency control. Content-Encoding handles compression, Last-Modified is for time-based checks (which can be imprecise), and Authorization handles identity, not concurrency.
From lesson: Request and Response Headers
When designing an API, why should the server include the 'Vary' header in its response?
Answer: To inform caches that the response depends on specific request headers. The Vary header tells caches that the response is subject to change based on headers like Accept-Encoding or Accept-Language. The other options are incorrect because Vary does not manage API versions, database metadata, or status code documentation.
From lesson: Request and Response Headers
Which of the following describes the correct use of the 'Accept' header in a RESTful request?
Answer: It tells the server which media types the client is capable of processing. The Accept header is for content negotiation, identifying what the client can parse. Content-Type describes the request body. HTTP methods are set by the verb, and payload size is managed by pagination or server limits, not the Accept header.
From lesson: Request and Response Headers
If a server receives a request with an 'If-None-Match' header matching the current ETag of the resource, what is the most appropriate response?
Answer: 304 Not Modified. 304 Not Modified signals that the cached version is still valid. 200 OK would be wasteful, 404 is for missing resources, and 412 is used when a precondition check fails, which is not the case here.
From lesson: Request and Response Headers
Why is it recommended to use the 'WWW-Authenticate' header in a 401 Unauthorized response?
Answer: To inform the client of the authentication scheme required to access the resource. WWW-Authenticate provides details on the challenge (e.g., Bearer, Basic) so the client knows how to format the credentials. It does not handle session duration, load balancing, or cache clearing.
From lesson: Request and Response Headers
How does HTTP/2 change the way REST APIs should be designed regarding resource representation?
Answer: It encourages granular resource design since multiplexing reduces the penalty of multiple requests.. HTTP/2's multiplexing allows multiple requests over one connection, removing the need for 'bundling' resources into one endpoint. Option 0 is wrong because bundling is less necessary; Option 2 is wrong because HATEOAS is architectural; Option 3 is wrong because content-type is independent of HTTP version.
From lesson: HTTP/2 and HTTP/3 Overview
Why is HTTP/3's use of QUIC advantageous for a high-traffic REST API on mobile networks?
Answer: It ensures that a single dropped packet does not block all concurrent requests on the connection.. QUIC handles streams independently at the transport layer, solving the head-of-line blocking issue present in TCP. Option 0 is unrelated to transport; Option 2 is handled by browser/CDN caches, not QUIC; Option 3 is security, which is independent of transport protocol.
From lesson: HTTP/2 and HTTP/3 Overview
When designing an API, which aspect of HTTP/2 header compression (HPACK) should a developer be aware of?
Answer: It makes long, descriptive REST resource paths 'cheaper' to send repeatedly.. HPACK uses static and dynamic tables to compress headers, making repeated headers (common in REST calls) very efficient. Option 1 is wrong because TLS is still required; Option 2 is false as HPACK is built-in; Option 3 is wrong because status codes are fundamental to HTTP.
From lesson: HTTP/2 and HTTP/3 Overview
In the context of REST API latency, what is the primary benefit of moving from HTTP/1.1 to HTTP/2?
Answer: Enabling more efficient utilization of a single TCP connection through stream concurrency.. HTTP/2 allows concurrent streams over a single connection, significantly reducing latency by avoiding the connection setup overhead of HTTP/1.1. Other options describe application-level concerns or constraints unrelated to transport protocol efficiency.
From lesson: HTTP/2 and HTTP/3 Overview
What happens if a client attempts to connect to a REST API via HTTP/3 but the server does not support it?
Answer: The client automatically falls back to HTTP/2 or HTTP/1.1 using established discovery mechanisms.. Clients use Alt-Svc headers or similar mechanisms to negotiate versions; if HTTP/3 fails, the protocol gracefully downgrades to lower versions. The other options describe non-standard or incorrect behaviors for HTTP negotiation.
From lesson: HTTP/2 and HTTP/3 Overview
How does the 'Stateless' constraint impact the design of an authentication mechanism?
Answer: Each request must carry the authentication credentials or a self-contained token. The correct answer is 1 because statelessness requires that the server does not store client context. Option 0 and 2 describe stateful behaviors. Option 3 is incorrect because REST supports secure authentication.
From lesson: REST Architectural Constraints
Which of the following best describes the 'Uniform Interface' constraint in practice?
Answer: Clients interact with resources through a standardized set of methods and representations. Option 1 is correct because Uniform Interface ensures predictability through standardized methods like GET/POST and resource representation. Options 0, 2, and 3 are irrelevant to the architectural constraint.
From lesson: REST Architectural Constraints
If a service provides a response that includes links to related resources, which constraint is being followed?
Answer: HATEOAS. HATEOAS (Hypermedia as the Engine of Application State) is the correct answer because it enables dynamic navigation of the API. The others do not specifically address resource linking and navigation.
From lesson: REST Architectural Constraints
Why is the 'Cacheable' constraint essential for large-scale distributed systems?
Answer: It reduces latency and network bandwidth by allowing re-use of previous responses. Caching minimizes redundant data transfers and processing, improving performance. Option 0 is a security risk, 1 is impossible, and 3 is incorrect as persistence isn't the primary goal.
From lesson: REST Architectural Constraints
What is the primary benefit of the 'Layered System' constraint?
Answer: It allows the deployment of load balancers, proxies, and gateways without modifying the client. Layered systems decouple the client from the server, allowing middle components to be introduced for security or load balancing. Option 1 contradicts decoupling; 2 and 3 are incorrect definitions.
From lesson: REST Architectural Constraints
Which URL design best represents the principle of resource-based naming for a specific comment belonging to a post?
Answer: /posts/5/comments/123. /posts/5/comments/123 uses nouns and hierarchical nesting, which correctly identifies a resource within a collection. The first option uses a verb, the third uses a verb-noun hybrid, and the fourth loses the context of the parent post.
From lesson: Resource Naming and URL Design
How should a search feature that filters users by 'active' status be represented?
Answer: /users?status=active. Query parameters are designed for filtering and sorting collections without changing the resource identifier. The other options treat 'active' as a sub-resource or use verbs, which violates REST constraints.
From lesson: Resource Naming and URL Design
When designing a URL for a resource collection, which practice is most consistent with REST principles?
Answer: Always use plural nouns to indicate a collection. Plural nouns are standard for collections. Using singular nouns for collections is confusing, including methods in URLs is redundant, and inconsistent casing makes an API unpredictable.
From lesson: Resource Naming and URL Design
What is the primary architectural benefit of maintaining flat URL structures?
Answer: It minimizes API coupling to the hierarchical storage implementation. Flat structures prevent the API contract from being strictly tied to deeply nested database relationships, allowing for internal refactoring. The other options are incorrect interpretations of API goals.
From lesson: Resource Naming and URL Design
Which of the following is the most standard approach to handling pagination in an API?
Answer: /products?page=2&size=10. Pagination should be handled through query parameters, as it represents a view state of the collection rather than a new resource. The other options incorrectly embed navigation metadata into the resource path.
From lesson: Resource Naming and URL Design
When deciding between URI versioning and Header versioning, which factor best dictates the choice?
Answer: Whether you want to leverage browser caching for resources. URI versioning is transparent to web caches, meaning a change in version URL acts as a new cache key. Header versioning is cleaner for RESTful principles but makes caching more complex, requiring the Vary header. The other options are irrelevant to the architectural trade-offs.
From lesson: API Versioning Strategies
A team introduces a non-breaking field to a JSON object in an existing version. What is the standard approach regarding versioning?
Answer: Maintain the current version, as this is an additive change. Non-breaking changes, such as adding a field or optional parameter, should not trigger a version bump, as clients ignoring unknown fields will continue to function. Bumping a version for non-breaking changes forces unnecessary upgrades. The other options are overkill for backwards-compatible additions.
From lesson: API Versioning Strategies
Why is it recommended to use a 'Sunset' header when deprecating an API version?
Answer: To inform the client of the specific date the version will cease to function. The Sunset HTTP header is the standard way to communicate the expiration date of an API version to clients. Providing a link, maintenance status, or experimental status does not solve the fundamental issue of communicating a firm cutoff date.
From lesson: API Versioning Strategies
If you follow REST principles, why might some architects dislike URI path versioning like /v1/resource?
Answer: Because it treats the version as part of the resource identifier rather than metadata. REST treats a URI as the identifier for a resource. Adding '/v1/' suggests that the resource itself changes identity, rather than just the representation. The other options are incorrect, as URI versioning is compatible with authentication, SSL, and mobile platforms.
From lesson: API Versioning Strategies
Which of the following describes the correct usage of Media Type versioning (Content Negotiation)?
Answer: Including the version in the Accept header via vendor-specific media types. Media type versioning involves headers like 'Accept: application/vnd.myapi.v1+json'. This keeps the URI clean and adheres to the spirit of REST content negotiation. File extensions, query parameters, and User-Agent sniffing are either non-standard or violate the core design intent of clean resource identification.
From lesson: API Versioning Strategies
A client sends a request to update a user's email address by providing the full user object to the URI /users/123. Which method is most appropriate?
Answer: PUT. PUT is correct because it replaces the entire resource representation. POST is for creating new resources or non-idempotent actions, GET is for retrieval only, and PATCH is for partial updates rather than full replacement.
From lesson: Idempotency and Safety
If a developer uses a GET request to trigger a payment process that charges a customer's credit card, why is this a violation of REST constraints?
Answer: It violates the requirement that GET must be safe. A safe method must not have side effects. Charging a credit card is a state-changing side effect, meaning GET is inappropriate. Idempotency is a separate property, and PUT/POST are for state changes, not efficiency.
From lesson: Idempotency and Safety
You have an endpoint that generates a PDF report based on a user's search criteria. Which HTTP method should you use to ensure compliance with REST principles?
Answer: GET. GET is appropriate here because generating a report (even if complex) does not modify the state of the server resources. POST, PUT, and PATCH imply state mutation, which is unnecessary for data retrieval.
From lesson: Idempotency and Safety
Why is the POST method considered non-idempotent?
Answer: Because it is specifically designed to create new resource instances each time it is executed. POST is defined as non-idempotent because multiple identical requests will result in multiple distinct resources being created. The other options are incorrect interpretations of its functional purpose.
From lesson: Idempotency and Safety
A system implements a PATCH endpoint to update a user's profile. Why might this implementation be non-idempotent despite PATCH technically being allowed to be idempotent?
Answer: Because the server implementation includes an increment operation like 'age = age + 1'. An operation like 'increment' is non-idempotent because repeated execution changes the state further each time. PATCH itself is a method that can be implemented idempotently, but the logic inside the request determines the result. The other options misstate the nature of PATCH.
From lesson: Idempotency and Safety
When a client asks for the 'next page' in a system using offset pagination, why might they receive duplicate data?
Answer: New items were inserted into the database before the next request, shifting previous records to earlier offsets.. Option 2 is correct because offset pagination relies on row position; insertions shift subsequent records. Options 1 and 4 describe implementation bugs, and Option 3 applies to cursor-based pagination, not offset.
From lesson: Pagination — Offset vs Cursor-based
Which of the following scenarios makes cursor-based pagination strictly superior to offset-based pagination?
Answer: The dataset is large, constantly changing, and requires high performance.. Option 3 is correct because cursors avoid expensive scans on large, changing datasets. Option 1 is actually a weakness of cursors, and Option 4 is an offset feature; Option 2 doesn't justify cursors.
From lesson: Pagination — Offset vs Cursor-based
What is the primary benefit of using an opaque cursor string in a REST API?
Answer: It hides the underlying database indexing strategy from the client.. Option 1 is incorrect as users can't calculate distance regardless. Option 2 is correct as it encapsulates the implementation. Option 3 is false, and Option 4 is wrong because clients don't calculate cursors.
From lesson: Pagination — Offset vs Cursor-based
How should a well-designed API handle an invalid or expired cursor provided by a client?
Answer: Return a 400 Bad Request error.. Option 0 is correct because an invalid cursor is a client-side error. Option 1 and 3 are bad API practice as they hide client mistakes. Option 2 is incorrect as the cursor represents a specific point in a stream that no longer exists.
From lesson: Pagination — Offset vs Cursor-based
Why is 'LIMIT' combined with 'OFFSET' generally avoided in high-scale REST APIs?
Answer: The database must scan and discard all rows preceding the offset, which is inefficient.. Option 1 is false. Option 2 is the correct reason (performance overhead). Option 3 is incorrect as sorting can still use indices. Option 4 is wrong because limit/offset works with any sort order.
From lesson: Pagination — Offset vs Cursor-based
When designing an endpoint to filter resources by status, which approach best adheres to REST constraints?
Answer: Appending query parameters like ?status=active to the resource URL. Query parameters are the standard mechanism for resource discovery and filtering. Option 0 is wrong because GET bodies are often ignored or unsupported; Option 2 breaks the resource-based URI structure; Option 3 is non-standard and brittle.
From lesson: Filtering, Sorting, and Searching
What is the primary benefit of using a standardized syntax (e.g., 'sort=-field') for sorting?
Answer: It provides a predictable, parsable interface for API consumers. A standard syntax provides a contract that clients can rely on without guessing implementation-specific details. Option 0 is incorrect because the API shouldn't dictate database internals; Option 1 is false; Option 3 is incorrect as the server must control the join logic to ensure security.
From lesson: Filtering, Sorting, and Searching
Why is it important to implement pagination when searching for resources?
Answer: To mitigate the risk of performance degradation from large dataset retrieval. Pagination protects the system from memory exhaustion and excessive latency. Option 0 is incorrect because clients often prefer to handle pagination themselves; Option 1 is not a standard benefit; Option 3 is incorrect as it usually adds complexity for the client.
From lesson: Filtering, Sorting, and Searching
When searching through a massive collection, why should you prefer query parameters over a POST body?
Answer: Query parameters make the state of the search idempotent and bookmarkable. REST design principles favor GET for resource retrieval so that the URI uniquely identifies the resource state, which allows for caching and sharing links. Option 0 is a limitation, not a benefit; Option 2 is false; Option 3 is a common misconception about network performance.
From lesson: Filtering, Sorting, and Searching
How should a well-designed API respond when a client requests a sort order on an unsupported or invalid field?
Answer: Return a 400 Bad Request error with a descriptive message. A 400 Bad Request indicates that the client provided an invalid parameter, preventing ambiguity. Option 0 is poor UX as the client thinks they sorted the data; Option 2 is for server bugs; Option 3 is misleading as the request failed, not the collection itself.
From lesson: Filtering, Sorting, and Searching
An API receives a request to create a user, but the 'email' field contains an invalid format. Which status code is the most appropriate?
Answer: 422 Unprocessable Entity. 422 is specifically for semantic errors where the syntax is correct but the content is invalid. 400 is for syntax errors, 201 is for success, and 500 implies a server-side crash.
From lesson: Request Validation and Error Responses
What is the primary benefit of returning a standardized error body containing a unique error code instead of just a message string?
Answer: It allows clients to implement localized or programmatically handled error logic.. Unique codes (e.g., 'INVALID_EMAIL') allow clients to react predictably, whereas dynamic strings are meant for human reading and are hard to parse programmatically.
From lesson: Request Validation and Error Responses
When a request requires multiple headers for validation and they are missing, what is the best practice?
Answer: Return a 400 error listing all missing or invalid fields in the response body.. Providing all validation errors at once improves developer experience by reducing round-trips. Ignoring them or using defaults is poor practice, and 500 is incorrect as it's not a server fault.
From lesson: Request Validation and Error Responses
If an API uses a POST request to update a resource and receives data that conflicts with the current state of the database, which code should be returned?
Answer: 409 Conflict. 409 Conflict is the standard for state-related mismatches. 400 implies malformed data, 404 implies the target doesn't exist, and 202 implies the request is merely queued.
From lesson: Request Validation and Error Responses
Which of the following describes the most secure way to handle a validation error in an API?
Answer: Returning a standardized error schema with an obfuscated server-side reference ID.. Standardized schemas keep the API contract clean, while reference IDs allow logs to be traced without exposing security-sensitive internals. The other options leak sensitive information.
From lesson: Request Validation and Error Responses
When a client requests a media type the server cannot provide, what is the most appropriate HTTP status code to return?
Answer: 406 Not Acceptable. 406 Not Acceptable is specifically designed for content negotiation failure. 400 is too generic, 415 is for incoming payloads (Content-Type) rather than requested responses, and 404 implies the resource itself is missing.
From lesson: Content Negotiation
Why is it considered a best practice to include 'Vary: Accept' in API responses?
Answer: To notify intermediaries and caches that the response varies based on the Accept header.. The Vary header instructs caches that the response might differ based on specific request headers. The other options describe header functionality unrelated to caching or resource representation.
From lesson: Content Negotiation
Which of the following describes the purpose of the 'Accept' header in a request?
Answer: It expresses the client's preference for the format of the server's response.. The Accept header is for the client to ask for specific representations. The first option describes Content-Type, the second describes Accept-Language, and the fourth describes Accept-Encoding.
From lesson: Content Negotiation
If a server receives a request with an 'Accept' header that lists multiple media types with different quality values (q-factors), how should the server behave?
Answer: It should prioritize the media type with the highest weight (q-value).. Quality values (q-factors) are intended to allow clients to weight their preferences. Ignoring them defeats the purpose of negotiation, and merging into multipart is not the standard behavior for basic content negotiation.
From lesson: Content Negotiation
What is the primary architectural benefit of separating resource identity from representation format in content negotiation?
Answer: It allows the API to evolve to support new formats without changing the resource URI.. Decoupling URI from format allows extensibility; adding a new format (e.g., YAML) doesn't require a new URL. The other options are incorrect because this has no impact on speed, documentation requirements, or client-side framework choices.
From lesson: Content Negotiation
When designing an API that uses OAuth2, why is the Authorization Code flow preferred over the Implicit flow?
Answer: The Authorization Code flow avoids exposing tokens in the browser URL redirect.. The Authorization Code flow is safer because tokens are exchanged via a secure back-channel rather than being returned in a URL fragment. The Implicit flow is deprecated because it exposes tokens in the browser history. The other options are incorrect as they misidentify the primary security trade-off.
From lesson: Authentication — API Keys, JWT, OAuth2
A developer wants to invalidate a user's session before the JWT expiration time. Which approach is most effective in a stateless REST architecture?
Answer: Maintain a server-side blacklist of jti (JWT ID) claims for revoked tokens.. Since JWTs are self-contained, the only way to invalidate them is to track the jti (unique token identifier) in a high-speed store (like Redis) and check it on every request. Deleting from local storage only hides the token, it doesn't invalidate the server-side access.
From lesson: Authentication — API Keys, JWT, OAuth2
Why is the 'Bearer' scheme specified in the Authorization header when using tokens?
Answer: It acts as a protocol requirement for OAuth2 to distinguish the credential type from Basic auth.. The 'Bearer' scheme tells the API how to parse the credentials. It signifies that the token itself confers access. Encrypted tokens are not 'Bearer' tokens in this context, and it is not a mechanism to enforce HTTPS or authorize without server-side validation.
From lesson: Authentication — API Keys, JWT, OAuth2
In a machine-to-machine API integration, why is it better to use a dedicated API Key rather than a user's session token?
Answer: API Keys can be scoped to specific services and easily revoked without affecting the user's account.. Separation of concerns is critical; API keys allow for service-specific permissions and lifecycle management. User tokens represent a specific user's identity and permissions, which is inappropriate for service automation. The other options are false because keys are not inherently more secure or automated.
From lesson: Authentication — API Keys, JWT, OAuth2
What is the primary security risk of 'refresh token rotation' failing to execute properly?
Answer: Old refresh tokens could be reused if they are not invalidated upon the issuance of a new pair.. Rotation requires that every time a refresh token is used, a new one is issued and the old one is invalidated. If rotation fails or the old token remains valid, an attacker who intercepted the old refresh token can use it to maintain persistence. The other choices describe logic errors or performance issues, not core security risks.
From lesson: Authentication — API Keys, JWT, OAuth2
Which of the following best describes the fundamental difference between RBAC and Scopes in a REST API?
Answer: RBAC defines long-term permissions for users, while scopes define short-term, granular permissions for an access token.. RBAC is typically mapped to user identity and organizational role, while scopes are scoped-down permissions issued to a client or request context. Option 0 is wrong because RBAC is about permission levels, not just identity. Option 2 is incorrect as both handle read/write. Option 3 is false as they are distinct authorization mechanisms.
From lesson: Authorization — RBAC and Scopes
When designing a secure API, why should you prefer scopes over static roles for third-party integrations?
Answer: Scopes allow for the principle of least privilege by limiting the token's access to only what is necessary.. Scopes allow developers to limit the blast radius of a token, which is essential for third-party access. Option 0 is not the primary reason. Option 2 is false as roles remain common. Option 3 is incorrect as scopes do not provide encryption.
From lesson: Authorization — RBAC and Scopes
A user has the 'Admin' role, but the requested operation requires the 'write:audit' scope. What should the API do?
Answer: Deny access if the provided access token lacks the 'write:audit' scope, regardless of the user's role.. RBAC and Scopes are distinct; having a high-level role doesn't grant implicit permission if the specific scope required for a restricted operation is missing. The other options suggest unsafe authorization logic by ignoring scope requirements.
From lesson: Authorization — RBAC and Scopes
How should an API handle an attempt to access a resource when the token is valid but the scope is insufficient?
Answer: Return a 403 Forbidden status code.. 403 Forbidden is the standard HTTP response for an authenticated user lacking the specific permissions (scopes) for a resource. 401 implies the user is not logged in; 404 is misleading; redirects are for UI/Browser flows, not API responses.
From lesson: Authorization — RBAC and Scopes
Why is it considered best practice to validate scopes at the resource server level rather than relying solely on the gateway?
Answer: To ensure internal services are protected even if the gateway is bypassed or misconfigured.. Defense-in-depth is the core reason; internal services must verify the token's scopes to ensure security is not solely dependent on a single perimeter check. Option 0 is false, Option 2 is incorrect regarding performance, and Option 3 is false because tokens are usually verified by a shared service.
From lesson: Authorization — RBAC and Scopes
A browser performs a preflight request. What is the primary purpose of this communication?
Answer: To check if the server allows the specific HTTP method and headers of the intended request.. The preflight request determines if the server permits the actual cross-origin request. TLS handshakes are separate; CSRF tokens are part of application logic; and authentication happens during the actual request, not the preflight.
From lesson: CORS — Cross-Origin Resource Sharing
When can a browser omit the OPTIONS preflight request for a cross-origin call?
Answer: When the request is a simple GET request using standard content types.. Simple requests (GET/HEAD/POST with specific media types) do not trigger a preflight. The others are incorrect because protocol or login status do not bypass the CORS spec, and public registries are irrelevant.
From lesson: CORS — Cross-Origin Resource Sharing
If your API needs to support cookies in a cross-origin request, what must be true?
Answer: The client must set the 'withCredentials' property to true and the server must return 'Access-Control-Allow-Credentials: true'.. Credentialed requests require explicit opt-in from both sides. Wildcards are forbidden with credentials, POST is not required, and browsers never bypass origin checks.
From lesson: CORS — Cross-Origin Resource Sharing
What happens if a server omits the 'Access-Control-Allow-Origin' header in its response to a request?
Answer: The browser blocks the response from the client-side code, resulting in an error.. CORS is a browser-enforced security model. If the header is missing, the browser blocks access to the response. It does not default to allowing it, warn only, or change the resource's origin status.
From lesson: CORS — Cross-Origin Resource Sharing
An API client sends a custom header 'X-Requested-By'. What must the server do to allow this request?
Answer: Include 'X-Requested-By' in the 'Access-Control-Allow-Headers' response header.. Custom headers must be explicitly whitelisted in the preflight response headers. Simply ignoring or using the wrong header field will result in a blocked request.
From lesson: CORS — Cross-Origin Resource Sharing
Which HTTP status code is specifically designed for signaling that a client has sent too many requests in a given amount of time?
Answer: 429 Too Many Requests. 429 is the standard code for rate limiting. 400 is for malformed syntax, 403 is for insufficient permissions, and 503 is for server maintenance or overload, not specifically client-side throttling.
From lesson: Rate Limiting
Why is it considered a best practice to return the 'Retry-After' header when a rate limit is hit?
Answer: It provides actionable information for the client to schedule future requests. The 'Retry-After' header allows clients to intelligently wait before retrying. Other options are incorrect because the time is variable, it doesn't indicate the endpoint, and it has nothing to do with authentication.
From lesson: Rate Limiting
What is the primary benefit of using a 'Token Bucket' algorithm over a 'Fixed Window' algorithm?
Answer: It allows for small bursts of traffic while enforcing a long-term average rate. Token Bucket permits short bursts, which is more realistic for API traffic, whereas Fixed Window creates 'cliffs' at window edges. It does require state, it consumes memory, and it does not eliminate status codes.
From lesson: Rate Limiting
If you are designing a public API, what is the best strategy for handling rate limits for unauthenticated users?
Answer: Apply a significantly stricter limit based on IP address. Restricting unauthenticated users by IP prevents abuse while allowing valid usage. Blocking them prevents discovery, identical limits encourage scraping, and no limits invite Denial-of-Service attacks.
From lesson: Rate Limiting
How should an API respond to a client that has exceeded its quota if the client is performing critical background operations?
Answer: Send an error code 429 and include rate-limit headers in the response. Standardized responses (429 + headers) allow the client to handle the delay gracefully. Silently dropping requests causes timeouts, ignoring limits creates fairness issues, and banning is an extreme overreaction to traffic volume.
From lesson: Rate Limiting
When designing a REST API, why is it considered insufficient to simply use HTTPS without validating the server certificate?
Answer: HTTPS only protects against eavesdropping, not the server's identity.. Option 0 is correct because HTTPS provides both encryption and identity verification; without validation, you are vulnerable to man-in-the-middle attacks. Options 1 and 3 are technically incorrect regarding how TLS functions, and option 2 is unrelated to latency.
From lesson: HTTPS and TLS
A developer is concerned about sensitive credentials being exposed in transit for a GET request. What is the most appropriate REST-compliant solution?
Answer: Upgrade the request to a POST method to move the data from the URL to the body.. Option 1 is correct because request bodies are protected by the TLS tunnel, unlike URL parameters which are often exposed in logs. Option 0 is a workaround, Option 2 is false as TLS does not encrypt path components, and Option 3 is poor practice.
From lesson: HTTPS and TLS
What is the primary security advantage of implementing mTLS in a microservices REST architecture?
Answer: It ensures that both the client and the server must prove their identities to each other.. Option 1 is correct because mTLS (mutual TLS) requires the client to present a certificate, ensuring bi-directional authentication. Options 0, 2, and 3 misrepresent the core function of mutual authentication.
From lesson: HTTPS and TLS
Why is it important to disable older TLS versions (e.g., TLS 1.0) on your API server?
Answer: To prevent attackers from exploiting known cryptographic weaknesses in outdated protocols.. Option 2 is correct; older TLS versions are prone to attacks like POODLE or BEAST. Options 0, 1, and 3 are incorrect as protocol versions do not affect data format, header size, or power consumption in this context.
From lesson: HTTPS and TLS
If an API client receives a '403 Forbidden' error immediately after establishing a TLS handshake, what is the most likely cause in an mTLS environment?
Answer: The client provided an invalid or untrusted certificate during the handshake.. Option 0 is correct because in mTLS, if the certificate is not recognized, the connection can be established but the server will restrict access. The other options describe problems that would likely result in different status codes (405, 413) or protocol negotiation errors.
From lesson: HTTPS and TLS
When defining an API resource that represents a collection, which structure is the most appropriate for representing a list of items in an OpenAPI 3.0 schema?
Answer: An array type with an items reference to a schema object. The array type is the standard way to represent collections in OpenAPI. Using 'list' or nested objects is non-standard, and maps are for key-value associations, not ordered collections.
From lesson: OpenAPI 3.0 and Swagger
If you need to define a required authentication header for every endpoint, where is the most efficient place to define it in your OpenAPI specification?
Answer: In the global components/securitySchemes section and the top-level security field. Defining it in the top-level 'security' field ensures consistency across the entire API, whereas defining it per operation is redundant. The 'info' object is for metadata, not security policy.
From lesson: OpenAPI 3.0 and Swagger
Which HTTP method should be specified in an OpenAPI operation if the client is submitting a request to create a new resource at a specific URI?
Answer: POST. POST is the standard method for creating a new resource as a subordinate of a collection. PUT is used for idempotent updates/replacements, GET for retrieval, and PATCH for partial updates.
From lesson: OpenAPI 3.0 and Swagger
What is the primary benefit of using '$ref' in an OpenAPI 3.0 document?
Answer: It allows for reusability of schema definitions across multiple endpoints. $ref is a JSON Reference that promotes modularity and DRY (Don't Repeat Yourself) design. It does not affect runtime speed, security, or implementation details.
From lesson: OpenAPI 3.0 and Swagger
When an endpoint returns a successful '201 Created' status, what is the best practice to communicate the location of the new resource in OpenAPI?
Answer: Using a 'headers' object to define the 'Location' field. The HTTP 'Location' header is the standard mechanism to indicate where a created resource exists. Custom body fields or placing data in the summary are not standard REST practices.
From lesson: OpenAPI 3.0 and Swagger
When documenting a complex resource, what is the most effective approach for 'getting started' content?
Answer: Include a sequential walkthrough of a common use case with example requests.. Option 1 is correct because narrative walkthroughs provide context, whereas the others are just reference material that lacks instructional value for new developers.
From lesson: API Documentation Best Practices
Why should you include 'cURL' snippets in your documentation?
Answer: Because it is a language-agnostic way to show how to interact with an endpoint.. Option 2 is correct because cURL is universal and helps developers understand the raw request structure, regardless of their preferred programming environment.
From lesson: API Documentation Best Practices
Which of the following describes the ideal way to document an HTTP status code 400?
Answer: Define the conditions under which it occurs and provide an example error body structure.. Option 2 is correct because developers need actionable info on field validation issues; the others fail to provide clarity or are dismissive.
From lesson: API Documentation Best Practices
What is the primary benefit of documenting request schemas using standardized formats like JSON Schema?
Answer: It allows tools to validate incoming requests and generate client code automatically.. Option 1 is correct because machine-readable schemas provide interoperability; they do not enhance security or replace human-written explanations.
From lesson: API Documentation Best Practices
How should you handle API versioning in documentation?
Answer: Maintain separate documentation sets for each version while highlighting the differences.. Option 1 is correct because it ensures stability for existing integrations; the others either cause data loss or lead to significant confusion.
From lesson: API Documentation Best Practices
When designing a test suite for a RESTful endpoint, why is it considered best practice to validate the response schema instead of just checking the HTTP status code?
Answer: A 200 status code only confirms the request was received, not that the data payload conforms to the expected contract. Option 2 is correct because a 200 OK does not guarantee valid data structure. Option 1 is false because status codes are application-level. Option 3 is false as schema validation is more resource-intensive. Option 4 is false because status codes are a core tenet of the protocol.
From lesson: Testing APIs with Postman
What is the primary benefit of using environment variables over global variables when testing different API environments?
Answer: Environment variables provide a scope-specific way to manage data without polluting the global workspace. Option 2 is correct as environments provide better separation of concerns. Option 1 is false as global variables persist. Option 3 is false as both can be used. Option 4 is false as neither is encrypted by default without extra configuration.
From lesson: Testing APIs with Postman
In a workflow where the second API call requires an ID generated by the first call, what is the most efficient way to handle this in a test suite?
Answer: Use a global variable that is updated in the Tests tab of the first request and referenced in the second. Option 2 is the correct automated approach. Option 1 is brittle and manual. Option 3 is inefficient. Option 4 ignores the automation capabilities of the tool.
From lesson: Testing APIs with Postman
Which of the following describes the correct approach to testing a destructive operation like a DELETE request?
Answer: Perform a GET request after the DELETE to ensure the resource no longer exists. Option 3 ensures the state change actually occurred as expected. Option 1 and 2 are insufficient as they don't confirm the deletion outcome. Option 4 is a dangerous practice that can lead to data loss.
From lesson: Testing APIs with Postman
Why should you use collection-level scripts instead of request-level scripts for common assertions?
Answer: Collection-level scripts are executed for every request in the collection, reducing code duplication. Option 2 is correct because it promotes DRY (Don't Repeat Yourself) principles. Option 1 is false. Option 3 is incorrect as they run sequentially. Option 4 is false because individual requests can also hold assertions.
From lesson: Testing APIs with Postman
What is the primary objective of implementing contract testing in a REST API architecture?
Answer: To verify that the consumer and provider agree on the schema and request/response structure. Contract testing validates interface compatibility. Option 0 describes performance testing, option 2 describes E2E testing, and option 3 describes security testing.
From lesson: Contract Testing
Why is it recommended to use fuzzy matching (like regex) instead of exact value matching in a contract?
Answer: To allow the API to return dynamic data like timestamps or generated IDs without failing the test. Dynamic data changes per request; exact matching causes flaky tests. Option 0 is irrelevant to logic, option 2 is a bad practice, and option 3 is false.
From lesson: Contract Testing
In a consumer-driven contract testing workflow, what happens if the provider makes a breaking change to their API?
Answer: The consumer's build fails during the contract verification step. Contract tests catch discrepancies before deployment. Option 0 is impossible, option 2 is a side effect of bad practices, and option 3 is not the primary purpose of contract verification.
From lesson: Contract Testing
Which of the following scenarios is best suited for contract testing?
Answer: Ensuring the API returns a '404 Not Found' when a requested resource does not exist. Contract testing verifies API responses to specific requests. Option 0 is a unit test, option 2 is a front-end test, and option 3 is infrastructure configuration.
From lesson: Contract Testing
How does contract testing improve the development lifecycle of distributed systems?
Answer: It allows teams to deploy changes with higher confidence that they haven't broken downstream consumers. Contract tests act as a safety net for cross-team deployments. Options 0, 2, and 3 are either false or incorrect descriptions of the purpose of contract testing.
From lesson: Contract Testing
Why is it important to measure the 99th percentile (P99) latency rather than just the average response time during an API load test?
Answer: P99 latency identifies the experience of the slowest users, which averages mask.. P99 captures the outliers that affect the worst-off users, whereas averages hide spikes. Option 0 is false, 2 is incorrect as latency != throughput, and 3 is false.
From lesson: Load Testing APIs
When load testing an API that uses JWT-based authentication, which part of the process is most likely to become a CPU bottleneck?
Answer: Cryptographic signature verification of the JWT token.. Cryptographic operations are CPU-intensive. While JSON parsing/serialization takes resources, signature verification is significantly heavier under high concurrent load. Headers are negligible.
From lesson: Load Testing APIs
What is the primary risk of using synthetic test data that does not mirror production data volume?
Answer: Database query execution plans may change as tables increase in size.. Databases optimize queries based on data distribution; small tables don't reveal performance issues inherent to scanning large tables. The other options are not inherent properties of API/DB performance.
From lesson: Load Testing APIs
If your API experiences a sudden rise in 503 Service Unavailable errors during a load test, what does this typically suggest?
Answer: The client is sending requests at a rate faster than the server can queue or process.. 503 indicates the server is overloaded or down for maintenance. It is the standard response for queue saturation. The other options describe client errors or positive outcomes.
From lesson: Load Testing APIs
How does implementing a 'ramp-up' period in your load testing strategy improve result accuracy?
Answer: It allows application caches and connection pools to reach a steady state.. A steady state is required to see how the system performs under sustained pressure, rather than the initial noise of startup tasks. Option 0 is irrelevant, 1 is a side effect, and 3 is not a goal.
From lesson: Load Testing APIs
Which approach is most appropriate for a resource that requires partial updates to its properties?
Answer: Use a PATCH request to send only the modified fields. PATCH is designed for partial updates, making it efficient for modifying specific fields. PUT requires replacing the whole object, which is bandwidth-heavy. GET and DELETE are semantically incorrect for update operations.
From lesson: REST API Interview Questions
When designing an API, which method should be used for idempotent creation operations?
Answer: PUT. PUT is idempotent; repeating the same PUT request multiple times results in the same state. POST is non-idempotent as it usually creates new instances. PATCH is generally non-idempotent depending on the implementation, and HEAD only retrieves headers.
From lesson: REST API Interview Questions
A client requests a resource that no longer exists after having existed previously. Which HTTP status code is most suitable?
Answer: 410 Gone. 410 Gone is the correct status for a resource that has been permanently removed. 404 is for resources that are not found (and potentially never existed). 400 and 403 signify different error conditions entirely.
From lesson: REST API Interview Questions
What is the primary purpose of Hypermedia as the Engine of Application State (HATEOAS)?
Answer: To allow clients to discover API functionality dynamically via links in responses. HATEOAS allows clients to interact with the API through links provided in responses, decoupling client knowledge from server architecture. It has nothing to do with compression, security, or database schemas.
From lesson: REST API Interview Questions
Why is it important to use standard HTTP methods instead of creating custom methods?
Answer: It ensures interoperability with standard tools, caches, and security frameworks. Standard methods (GET, POST, etc.) ensure that caches, proxies, and security software handle the traffic correctly. Custom methods break this contract. Standard methods have no inherent speed advantage, and documentation can technically describe anything.
From lesson: REST API Interview Questions
When designing a public API intended for consumption by various third-party web clients, which protocol typically offers the best balance of caching, compatibility, and simplicity?
Answer: REST. REST uses standard HTTP methods that work with all browser caches and proxies. gRPC requires Protobufs and HTTP/2 which browsers struggle to support natively. GraphQL has complex caching needs. WebSockets are stateful and not designed for simple resource retrieval.
From lesson: REST vs GraphQL vs gRPC
A team needs to perform strict type checking between microservices that require high-performance, low-latency communication. Which approach is most efficient?
Answer: gRPC. gRPC uses binary serialization (Protobuf), which is much faster and smaller than text-based JSON used in REST or GraphQL. SOAP is outdated and verbose. REST and GraphQL suffer from overhead of parsing JSON.
From lesson: REST vs GraphQL vs gRPC
In which scenario would GraphQL be definitively superior to REST?
Answer: When the client needs to aggregate data from multiple entities in a single, flexible request. GraphQL allows clients to request exactly what they need from multiple resources, avoiding the 'N+1' or over-fetching issues common in REST. REST excels at CDN caching and simplicity. gRPC is better for pure performance. GraphQL has higher server overhead than REST.
From lesson: REST vs GraphQL vs gRPC
Why is it difficult to use standard HTTP caching headers with GraphQL?
Answer: Because GraphQL queries are often sent via POST, which many caches do not cache by default. Most GraphQL implementations use POST requests for queries to handle large parameters, and standard HTTP caches treat POST as non-idempotent/unsafe. REST and simple GET-based protocols work seamlessly with caches. The other options are incorrect interpretations of how protocols interact.
From lesson: REST vs GraphQL vs gRPC
When designing for resource-oriented architecture, why is it considered a best practice in REST to avoid deep nested endpoints?
Answer: Because resource relationships should ideally be handled via hypermedia or query parameters to keep resources intuitive. REST promotes resource-based URI design; excessive nesting (e.g., /a/b/c/d) complicates maintenance and doesn't represent true resources well. Hypermedia (HATEOAS) or simple filters are cleaner. The other options refer to non-existent or irrelevant technical limitations.
From lesson: REST vs GraphQL vs gRPC