API Security Documentation — OAuth2, API Keys, Rate Limiting
Practice documenting API security schemes: API key authentication, OAuth2 flows, Bearer tokens, scopes, rate limiting, CORS, and security best practices in OpenAPI specs.
0 / 32 completed
1 / 32
How are security schemes defined and applied in OpenAPI 3.x?
OpenAPI security pattern: define in components/securitySchemes (e.g., BearerAuth, ApiKeyAuth, OAuth2), then reference by name at the global level (applies to all operations) or override per operation. An empty security array ([]) on an operation means that operation is public. This separation of definition from application keeps specs DRY and makes security auditing straightforward — reviewers can check all schemes in one place.
2 / 32
What is the correct OpenAPI vocabulary for documenting OAuth2 scopes?
OpenAPI OAuth2 scope documentation: under securitySchemes > YourOAuth2 > flows > authorizationCode > scopes: { 'read:orders': 'Read order history and status', 'write:orders': 'Create and modify orders', 'admin:users': 'Manage user accounts (admin only)' }. Then on each operation: security: [{ OAuth2: ['read:orders'] }]. Documenting scopes with clear descriptions helps consumers request only the permissions they need, following the principle of least privilege.
3 / 32
How should rate limiting be documented in an API specification?
Complete rate limit documentation: (1) In endpoint description: 'Rate limit: 100 requests per 15-minute window per API key.' (2) In response headers schema: X-RateLimit-Limit (total allowed), X-RateLimit-Remaining (remaining in window), X-RateLimit-Reset (Unix timestamp when window resets), Retry-After (seconds until retry allowed). (3) 429 response body with RFC 7807 format. (4) Burst limits vs. sustained limits if both apply. Undocumented rate limits cause surprise outages for consumers.
4 / 32
What is the difference between 'http' type with 'bearer' scheme and 'apiKey' type in OpenAPI security schemes?
http/bearer: Authorization: Bearer eyJhbGciOiJSUzI1NiJ9... — typically a JWT with expiry and claims, issued via OAuth2 or an auth server. apiKey: X-API-Key: sk-abc123... or ?api_key=sk-abc123 — typically an opaque long-lived secret. Document apiKey location (header/query/cookie), the header name, and key rotation guidance. For bearer, document token expiry, refresh flow, and the issuer. Both should document what to do when the credential is compromised.
5 / 32
How should CORS (Cross-Origin Resource Sharing) be documented in an API specification?
CORS documentation matters for browser-based consumers. Document: Access-Control-Allow-Origin (list allowed origins or wildcard), Access-Control-Allow-Credentials (true if cookies/auth headers sent with credentials), Access-Control-Allow-Headers (custom headers your API accepts), Access-Control-Expose-Headers (custom headers your API exposes beyond CORS-safelisted ones like X-RateLimit-*), Access-Control-Max-Age (preflight cache duration). Include a note like: 'If you are integrating from a browser, contact support to allowlist your origin.' Undocumented CORS causes confusing integration failures.
6 / 32
Reviewer Comment:
"I'm seeing that you're using a simple API key for authentication. While it works, it doesn't align with our team's security standards. We need to ensure we're leveraging OAuth2 for user authorization and protecting against potential key exposure. Could you elaborate on why you chose this approach?"
This question tests understanding of the practical implications of security choices during code reviews. The correct answer demonstrates willingness to learn and acknowledges the reviewer's concerns about OAuth2's superior security model for user authorization. Options A and D represent a lack of awareness or prioritization of security best practices, while option C incorrectly suggests an API key is sufficient regardless of traffic volume – a common misunderstanding. The reviewer is highlighting a critical gap in your approach.
7 / 32
PR Description
Subject: Implement User Profile API Endpoint
This PR introduces a new endpoint to retrieve user profile information. Authentication is handled via an API key passed in the `X-API-Key` header.
Note: This is a simplified implementation for demonstration purposes.
This question assesses understanding of best practices regarding API security. While an API key can be a starting point, solely relying on it for authentication is often insufficient in production environments. OAuth2 provides significantly better protection by delegating authorization and minimizing the risk of exposing sensitive credentials—the PR description itself highlights this simplification as potentially problematic. Using OAuth2 would involve a flow where the client application receives tokens that represent user consent to access resources, rather than directly storing an API key.
8 / 32
During a code review of a new PR for our 'Phoenix' e-commerce platform's API, Sarah (Senior Security Engineer) comments: "Hey, I noticed you're using an API key for authentication. While it's quick to implement, it doesn't fully address the risks associated with storing and transmitting sensitive credentials. Specifically, consider how this key might be exposed in a logging system or inadvertently included in a public-facing documentation page. Let's discuss incorporating OAuth2 flow – particularly the Authorization Code grant – to provide a more robust and secure user authorization mechanism."
Sarah's comment correctly identifies a key security weakness: API keys are inherently less secure than OAuth2 for user authorization. While API keys can be sufficient in limited contexts, they're vulnerable to exposure and compromise if not handled extremely carefully. OAuth2 provides a standardized framework – particularly the Authorization Code grant – that mitigates these risks by abstracting the user credentials and relying on trusted intermediaries. The options presented misinterpret Sarah's concern; it isn't simply about 'quick implementation,' but rather a fundamental security best practice.
9 / 32
During a code review of the Phoenix e-commerce platform's API, Sarah (Senior Security Engineer) raises concerns about using an API key for authentication. She specifically highlights potential risks like exposure in logging systems and documentation. Which of the following statements BEST captures her central argument regarding the chosen authentication method?
The use of an API key presents a significant security vulnerability due to its inherent limitations in managing user authorization and protecting against credential leakage, necessitating a more robust solution like OAuth2.
Sarah's concern isn't about the *technical* limitations of API keys themselves – they are fine for simpler scenarios. Instead, she focuses on their inherent vulnerabilities regarding user authorization and credential security. An API key is a single secret that needs to be managed carefully, whereas OAuth2 provides a layered approach with scopes and token rotation, significantly reducing the risk of exposure or misuse. Option A is incorrect as it states the key is secure; option B dismisses her valid concerns, and options C & D misrepresent the core issue.
10 / 32
Reviewer Comment:
"I'm seeing that you're using a simple API key for authentication. While it works, it doesn't align with our team's security standards. We need to ensure we're leveraging OAuth2 for user authorization and protecting against potential key exposure. Could you elaborate on why you chose this approach?"
This question tests understanding of the practical implications of security choices during code reviews. The correct answer demonstrates willingness to learn and acknowledges the reviewer's concerns about OAuth2's superior security model for user authorization. Options A and D represent a lack of awareness or prioritization of security best practices, while option C incorrectly suggests an API key is sufficient regardless of traffic volume – a common misunderstanding. The reviewer is highlighting a critical gap in your approach.
11 / 32
PR Description
Subject: Implement User Profile API Endpoint
This PR introduces a new endpoint to retrieve user profile information. Authentication is handled via an API key passed in the `X-API-Key` header.
Note: This is a simplified implementation for demonstration purposes.
This question assesses understanding of best practices regarding API security. While an API key can be a starting point, solely relying on it for authentication is often insufficient in production environments. OAuth2 provides significantly better protection by delegating authorization and minimizing the risk of exposing sensitive credentials—the PR description itself highlights this simplification as potentially problematic. Using OAuth2 would involve a flow where the client application receives tokens that represent user consent to access resources, rather than directly storing an API key.
12 / 32
During a code review of a new PR for our 'Phoenix' e-commerce platform's API, Sarah (Senior Security Engineer) comments: "Hey, I noticed you're using an API key for authentication. While it's quick to implement, it doesn't fully address the risks associated with storing and transmitting sensitive credentials. Specifically, consider how this key might be exposed in a logging system or inadvertently included in a public-facing documentation page. Let's discuss incorporating OAuth2 flow – particularly the Authorization Code grant – to provide a more robust and secure user authorization mechanism."
Sarah's comment correctly identifies a key security weakness: API keys are inherently less secure than OAuth2 for user authorization. While API keys can be sufficient in limited contexts, they're vulnerable to exposure and compromise if not handled extremely carefully. OAuth2 provides a standardized framework – particularly the Authorization Code grant – that mitigates these risks by abstracting the user credentials and relying on trusted intermediaries. The options presented misinterpret Sarah's concern; it isn't simply about 'quick implementation,' but rather a fundamental security best practice.
13 / 32
During a code review of the Phoenix e-commerce platform's API, Sarah (Senior Security Engineer) raises concerns about using an API key for authentication. She specifically highlights potential risks like exposure in logging systems and documentation. Which of the following statements BEST captures her central argument regarding the chosen authentication method?
The use of an API key presents a significant security vulnerability due to its inherent limitations in managing user authorization and protecting against credential leakage, necessitating a more robust solution like OAuth2.
Sarah's concern isn't about the *technical* limitations of API keys themselves – they are fine for simpler scenarios. Instead, she focuses on their inherent vulnerabilities regarding user authorization and credential security. An API key is a single secret that needs to be managed carefully, whereas OAuth2 provides a layered approach with scopes and token rotation, significantly reducing the risk of exposure or misuse. Option A is incorrect as it states the key is secure; option B dismisses her valid concerns, and options C & D misrepresent the core issue.
14 / 32
Reviewer Comment:
"I'm seeing that you're using a simple API key for authentication. While it works, it doesn't align with our team's security standards. We need to ensure we're leveraging OAuth2 for user authorization and protecting against potential key exposure. Could you elaborate on why you chose this approach?"
This question tests understanding of the practical implications of security choices during code reviews. The correct answer demonstrates willingness to learn and acknowledges the reviewer's concerns about OAuth2's superior security model for user authorization. Options A and D represent a lack of awareness or prioritization of security best practices, while option C incorrectly suggests an API key is sufficient regardless of traffic volume – a common misunderstanding. The reviewer is highlighting a critical gap in your approach.
15 / 32
PR Description
Subject: Implement User Profile API Endpoint
This PR introduces a new endpoint to retrieve user profile information. Authentication is handled via an API key passed in the `X-API-Key` header.
Note: This is a simplified implementation for demonstration purposes.
This question assesses understanding of best practices regarding API security. While an API key can be a starting point, solely relying on it for authentication is often insufficient in production environments. OAuth2 provides significantly better protection by delegating authorization and minimizing the risk of exposing sensitive credentials—the PR description itself highlights this simplification as potentially problematic. Using OAuth2 would involve a flow where the client application receives tokens that represent user consent to access resources, rather than directly storing an API key.
16 / 32
During a code review of a new PR for our 'Phoenix' e-commerce platform's API, Sarah (Senior Security Engineer) comments: "Hey, I noticed you're using an API key for authentication. While it's quick to implement, it doesn't fully address the risks associated with storing and transmitting sensitive credentials. Specifically, consider how this key might be exposed in a logging system or inadvertently included in a public-facing documentation page. Let's discuss incorporating OAuth2 flow – particularly the Authorization Code grant – to provide a more robust and secure user authorization mechanism."
Sarah's comment correctly identifies a key security weakness: API keys are inherently less secure than OAuth2 for user authorization. While API keys can be sufficient in limited contexts, they're vulnerable to exposure and compromise if not handled extremely carefully. OAuth2 provides a standardized framework – particularly the Authorization Code grant – that mitigates these risks by abstracting the user credentials and relying on trusted intermediaries. The options presented misinterpret Sarah's concern; it isn't simply about 'quick implementation,' but rather a fundamental security best practice.
17 / 32
During a code review of the Phoenix e-commerce platform's API, Sarah (Senior Security Engineer) raises concerns about using an API key for authentication. She specifically highlights potential risks like exposure in logging systems and documentation. Which of the following statements BEST captures her central argument regarding the chosen authentication method?
The use of an API key presents a significant security vulnerability due to its inherent limitations in managing user authorization and protecting against credential leakage, necessitating a more robust solution like OAuth2.
Sarah's concern isn't about the *technical* limitations of API keys themselves – they are fine for simpler scenarios. Instead, she focuses on their inherent vulnerabilities regarding user authorization and credential security. An API key is a single secret that needs to be managed carefully, whereas OAuth2 provides a layered approach with scopes and token rotation, significantly reducing the risk of exposure or misuse. Option A is incorrect as it states the key is secure; option B dismisses her valid concerns, and options C & D misrepresent the core issue.
18 / 32
Reviewer Comment:
"I'm seeing that you're using a simple API key for authentication. While it works, it doesn't align with our team's security standards. We need to ensure we're leveraging OAuth2 for user authorization and protecting against potential key exposure. Could you elaborate on why you chose this approach?"
This question tests understanding of the practical implications of security choices during code reviews. The correct answer demonstrates willingness to learn and acknowledges the reviewer's concerns about OAuth2's superior security model for user authorization. Options A and D represent a lack of awareness or prioritization of security best practices, while option C incorrectly suggests an API key is sufficient regardless of traffic volume – a common misunderstanding. The reviewer is highlighting a critical gap in your approach.
19 / 32
PR Description
Subject: Implement User Profile API Endpoint
This PR introduces a new endpoint to retrieve user profile information. Authentication is handled via an API key passed in the `X-API-Key` header.
Note: This is a simplified implementation for demonstration purposes.
This question assesses understanding of best practices regarding API security. While an API key can be a starting point, solely relying on it for authentication is often insufficient in production environments. OAuth2 provides significantly better protection by delegating authorization and minimizing the risk of exposing sensitive credentials—the PR description itself highlights this simplification as potentially problematic. Using OAuth2 would involve a flow where the client application receives tokens that represent user consent to access resources, rather than directly storing an API key.
20 / 32
During a code review of a new PR for our 'Phoenix' e-commerce platform's API, Sarah (Senior Security Engineer) comments: "Hey, I noticed you're using an API key for authentication. While it's quick to implement, it doesn't fully address the risks associated with storing and transmitting sensitive credentials. Specifically, consider how this key might be exposed in a logging system or inadvertently included in a public-facing documentation page. Let's discuss incorporating OAuth2 flow – particularly the Authorization Code grant – to provide a more robust and secure user authorization mechanism."
Sarah's comment correctly identifies a key security weakness: API keys are inherently less secure than OAuth2 for user authorization. While API keys can be sufficient in limited contexts, they're vulnerable to exposure and compromise if not handled extremely carefully. OAuth2 provides a standardized framework – particularly the Authorization Code grant – that mitigates these risks by abstracting the user credentials and relying on trusted intermediaries. The options presented misinterpret Sarah's concern; it isn't simply about 'quick implementation,' but rather a fundamental security best practice.
21 / 32
During a code review of the Phoenix e-commerce platform's API, Sarah (Senior Security Engineer) raises concerns about using an API key for authentication. She specifically highlights potential risks like exposure in logging systems and documentation. Which of the following statements BEST captures her central argument regarding the chosen authentication method?
The use of an API key presents a significant security vulnerability due to its inherent limitations in managing user authorization and protecting against credential leakage, necessitating a more robust solution like OAuth2.
Sarah's concern isn't about the *technical* limitations of API keys themselves – they are fine for simpler scenarios. Instead, she focuses on their inherent vulnerabilities regarding user authorization and credential security. An API key is a single secret that needs to be managed carefully, whereas OAuth2 provides a layered approach with scopes and token rotation, significantly reducing the risk of exposure or misuse. Option A is incorrect as it states the key is secure; option B dismisses her valid concerns, and options C & D misrepresent the core issue.
22 / 32
A developer is using the Postman API client to test a new endpoint. The response includes this JSON: {
"status": "200",
"data": {
"user_id": 123,
"username": "john.doe"
}
}. Which statement best describes the API's response status code?
A 200 status code indicates successful execution of the API endpoint. The JSON payload contains user-specific data, confirming that the request was processed correctly and returned the requested information. Options B, C, and D represent other potential HTTP status codes indicating errors or timeouts.
23 / 32
// Python example - simulating an API response with rate limiting
import time
def get_data(key):
# Simulate API call delay and potential rate limit
time.sleep(1)
if key == 'valid_key':
return {'data': 'User data'}
else:
return {'error': 'Rate Limit Exceeded'}
What does the `time.sleep(1)` function in this code snippet represent within an API context?
The `time.sleep(1)` function simulates a delay introduced by an API server when it's experiencing high traffic or needs to enforce rate limiting. This prevents excessive requests and protects the server from overload. It's a common technique for modeling realistic API behavior.
24 / 32
Mark is writing a PR description for a new API endpoint that uses OAuth2 authentication. Which of the following statements best describes the key benefit of using OAuth2 in this scenario?
OAuth2's core benefit is granting limited access to resources without requiring users to share their credentials. The authorization grant obtained through OAuth2 allows the API to request specific data on behalf of the user, enhancing security by reducing the risk of credential exposure. Options A and D are incorrect; OAuth2 doesn't eliminate credential storage or automatically encrypt traffic.
25 / 32
You're reviewing a PR that implements a new user profile API. The developer has chosen to use an API key for authentication. Which of the following is the *most significant* security risk associated with this approach?
The core vulnerability with API keys is that they represent a single point of failure. If an API key is leaked or stolen, an attacker can gain unauthorized access to user data. Storing them in source control (option A) exacerbates this risk. While rate limiting may mitigate some issues, it doesn't address the fundamental problem of exposing credentials.
26 / 32
A Slack message from a developer states: "I've added an API key to the request header for authentication. It's quick and easy!" What is the *most concerning* aspect of this statement from a security perspective?
While using a header *can* be secure, the developer's emphasis on 'quick and easy' suggests they haven't considered the inherent risks of exposing an API key in this way. API keys should ideally be handled more securely (e.g., stored as environment variables) to prevent accidental exposure or compromise. Prioritizing ease-of-use over security is a critical mistake.
27 / 32
You're designing an API with rate limiting in place. What is the *primary* purpose of this feature?
Rate limiting is designed to protect an API from abuse. By restricting the number of requests a client can make within a certain time period, it prevents denial-of-service attacks and other malicious activities that could overload the system. While rate limiting contributes to security, its primary goal isn't encryption or billing.
28 / 32
Sarah, a Senior Security Engineer, is reviewing a PR for a new user profile API endpoint. The developer has implemented authentication using an API key in the `X-API-Key` header. Which of the following statements best reflects Sarah's primary concern? Using an API key directly exposes the key to potential compromise and unauthorized access, bypassing more secure methods like OAuth2.
Sarah's concern is about the lack of robust security controls associated with API keys. API keys provide no inherent user authorization and are susceptible to exposure if not handled carefully. OAuth2 offers a more secure approach by delegating authentication responsibilities.
29 / 32
You're designing an API that requires rate limiting. Which of the following statements accurately describes the *primary* purpose of this feature? Rate limiting prevents abuse and malicious attacks by restricting the number of requests a user or client can make within a given timeframe, protecting your server resources and ensuring fair usage.
The core function of rate limiting is to mitigate abuse and protect against malicious actors. By controlling the rate of requests, you safeguard your infrastructure from overload and ensure fair access for legitimate users.
30 / 32
During a code review, a developer uses an API key to authenticate requests. Which of the following is the *most significant* security risk associated with this approach? An API key can be easily exposed through logging or insecure storage, granting unauthorized access to sensitive data and potentially leading to account compromise.
The central vulnerability with API keys is their ease of exposure. Logging, insecure storage practices, or compromised environments can quickly grant unauthorized access. OAuth2 offers superior control and revocation capabilities.
31 / 32
"Hey team, just added an API key to the headers for this new integration. Should be working smoothly!" - David.
What is the *most critical* concern a security engineer would have regarding David's statement?
This scenario focuses on the potential dangers of casually sharing API keys. While David may have technically set up the headers correctly, the core issue is the *exposure* of the key through logs or monitoring tools. Options A and B are irrelevant to the immediate concern; option C accurately identifies this risk.
32 / 32
"Mark: I'm working on implementing rate limiting for the new user profile API. We're using a token bucket algorithm to limit requests per IP address. It's crucial to prevent abuse and potential denial-of-service attacks."
This question assesses understanding of the core function of rate limiting. While token buckets are a common algorithm, the *primary* purpose is to mitigate abuse and prevent denial-of-service attacks. Options A and D present misconceptions; Option B focuses on an implementation detail rather than the overall goal.
What will I practice in "API Security Documentation — OAuth2, API Keys, Rate Limiting"?
This is an API Spec Writing exercise set. It walks through 32 scenario-based multiple-choice questions built around real usage of API Spec Writing terminology that IT professionals encounter on the job.
Is this exercise free to use?
Yes. Every exercise on CoderSlingo, including this one, is free to complete with no account, sign-up, or paywall.
How many questions are in this exercise?
This set contains 32 questions. Each one shows immediate feedback and a detailed explanation after you answer, so you learn the correct usage right away rather than waiting for a final score.
Do I need prior experience to complete this exercise?
No prior experience is required. Each question includes a full explanation covering the reasoning behind the correct answer, so the exercise itself teaches the API Spec Writing vocabulary as you go.
Can I retry the exercise if I get questions wrong?
Yes — use the "Try again" button on the results screen to reset your answers and go through all the questions again. There is no limit on attempts.
Is my progress saved?
Your answers and score for the current session are tracked in the browser as you go. No account or login is needed, and there is nothing to install.
What if I don't understand a term used in a question?
Read the explanation shown after you answer each question — it breaks down the correct term in plain English with a real-world example. You can also check the site Glossary for quick definitions.
How is this different from reading a blog article on the topic?
Exercises like this one are interactive drills that test and reinforce specific vocabulary through multiple-choice questions, while blog articles explain concepts in prose. Practising here after reading builds active recall, not just passive recognition.
Where can I find more API Spec Writing exercises?
See the API Spec Writing exercises hub for the full set of related pages, or browse all exercise categories from the main Exercises index.
Can I use this exercise to prepare for a technical interview?
Yes — API Spec Writing vocabulary comes up often in technical discussions and interviews. Pair this exercise with our dedicated Interview Preparation section for role-specific practice.