Skip to content

API Design Requirements

User Scenarios & Testing

User Story 1 - Basic API Authentication (Priority: P1)

The Conference Expo frontend application and internal services need to authenticate with the API using email/password credentials, receive tokens for session management, and make authenticated requests to protected endpoints.

Why this priority: Core functionality - without basic authentication, no API access is possible. This is the foundation for all other API interactions. This covers user login and server-to-server authentication for the platform's own clients.

Independent Test: Can be fully tested by implementing authentication endpoints, attempting login with valid/invalid credentials, receiving tokens, and using those tokens to access a protected test endpoint. Delivers immediate value by enabling secure API access for the platform.

Acceptance Scenarios:

  1. Given a user with valid email and password credentials, When they POST to the authentication endpoint, Then they receive a response containing access token, refresh token, token type, and expiration details
  2. Given an authenticated user with an expired access token but valid refresh token, When they POST to the token refresh endpoint, Then they receive a new access token without re-authenticating
  3. Given an authenticated user, When they include their access token in the Authorization header of a protected endpoint request, Then the API validates the token and processes the request
  4. Given a user with invalid credentials, When they attempt to authenticate, Then they receive a 401 Unauthorized response with a clear error message that doesn't reveal which credential was incorrect
  5. Given an authenticated user, When they POST to the logout endpoint with their tokens, Then their refresh token is revoked and they receive a 200 success response
  6. Given a user who has forgotten their password, When they POST to the password reset endpoint, Then they receive a time-limited reset link via email to update their password

User Story 2 - API Error Handling and Validation (Priority: P1)

API consumers need clear, consistent error responses when requests fail due to validation errors, authentication issues, authorization problems, or server errors so they can handle failures gracefully and provide appropriate feedback to end users.

Why this priority: Critical for developer experience and application stability. Poor error handling leads to confusion, increased support burden, and applications that cannot fail gracefully.

Independent Test: Can be fully tested by sending various invalid requests (malformed data, missing required fields, wrong types, unauthorized access attempts) and verifying response structure, status codes, and error messages follow consistent patterns.

Acceptance Scenarios:

  1. Given a developer sends a request with missing required fields, When the API validates the request, Then it returns a 400 Bad Request with detailed validation errors listing each missing field
  2. Given a developer sends a request with invalid data types, When the API validates the request, Then it returns a 400 Bad Request with clear error messages indicating expected vs provided types
  3. Given an unauthenticated user attempts to access a protected endpoint, When the API checks authentication, Then it returns a 401 Unauthorized with a message indicating authentication is required
  4. Given an authenticated user attempts to access a resource they don't have permission for, When the API checks authorization, Then it returns a 403 Forbidden with a message indicating insufficient permissions
  5. Given a developer requests a resource that doesn't exist, When the API attempts to retrieve it, Then it returns a 404 Not Found with a clear message
  6. Given a server error occurs during request processing, When the API encounters the error, Then it returns a 500 Internal Server Error with a safe error message and logs detailed error information for debugging
  7. Given a developer sends a request that violates rate limits, When the API checks rate limits, Then it returns a 429 Too Many Requests with retry-after information

User Story 3 - Passwordless Authentication (Priority: P2)

Users need an alternative authentication method that doesn't require remembering passwords, using email-based verification codes to access the platform securely via the API.

Why this priority: Enhances security and user experience by providing a modern alternative to passwords, but email/password authentication is sufficient for launch. This is a valuable enhancement for improving user experience.

Independent Test: Can be fully tested by implementing passwordless authentication endpoint, requesting verification code, receiving email, submitting code, and receiving authentication tokens.

Acceptance Scenarios:

  1. Given a user choosing passwordless authentication, When they POST their email address to the passwordless authentication endpoint, Then they receive a time-limited verification code via email
  2. Given a user with a valid verification code, When they POST the code to the verification endpoint, Then they receive authentication tokens and can access the platform
  3. Given a user with an expired verification code, When they attempt to use it, Then the API returns a 401 Unauthorized with a message indicating the code has expired
  4. Given a user requesting too many verification codes, When rate limits are exceeded, Then the API returns a 429 Too Many Requests response

User Story 4 - Third-Party OAuth Authorization Flow (Priority: P3)

Third-party application developers need to integrate with the Conference Expo API through an OAuth-style authorization flow where users grant specific permissions to their application, enabling secure delegated access without sharing credentials.

Why this priority: Important for future ecosystem growth and integrations, but not needed for platform launch. The platform serves its core purpose without external third-party integrations. This enables future extensibility.

Independent Test: Can be fully tested by implementing OAuth endpoints, creating a test third-party client registration, walking through authorization flow with user consent screen, receiving scoped tokens, and verifying scope-based access control on protected endpoints.

Acceptance Scenarios:

  1. Given a third-party application is registered with the platform, When they initiate the OAuth flow with requested scopes, Then the user is presented with a consent screen showing the application details and requested permissions
  2. Given a user reviews a third-party authorization request, When they approve the requested scopes, Then the application receives an authorization code it can exchange for access tokens
  3. Given a third-party application has an authorization code, When they POST to the token exchange endpoint, Then they receive access and refresh tokens limited to the approved scopes
  4. Given a third-party application with limited scopes, When they attempt to access an endpoint outside their approved scopes, Then the API returns a 403 Forbidden with scope violation details
  5. Given a user wants to revoke third-party access, When they revoke authorization, Then the third-party's refresh token is immediately invalidated and existing access tokens expire within 15 minutes
  6. Given a third-party application attempts to access a 2FA-protected scope, When the API validates the request, Then it requires valid 2FA verification before granting access

User Story 5 - API Documentation and Discovery (Priority: P2)

Developers integrating with the API need comprehensive, accurate, and interactive documentation that describes available endpoints, request/response schemas, authentication requirements, and allows them to test requests directly from the documentation.

Why this priority: Critical for developer adoption and reducing integration time, but the API can technically function without external documentation. The auto-generated Swagger documentation from NestJS provides this capability.

Independent Test: Can be fully tested by implementing NestJS decorators and DTOs that generate Swagger documentation, accessing the Swagger UI endpoint, verifying all endpoints are documented with correct schemas, and successfully executing test requests through the Swagger interface.

Acceptance Scenarios:

  1. Given a developer accesses the API documentation endpoint, When they view the Swagger UI, Then they see a complete list of all available endpoints organized by resource type
  2. Given a developer views an endpoint in the documentation, When they examine its details, Then they see request parameters, request body schema, response schemas for each status code, authentication requirements, and required scopes
  3. Given a developer wants to test an endpoint, When they use the "Try it out" feature in Swagger UI with their authentication token, Then they can execute real API requests and see actual responses
  4. Given a developer views a data model in the documentation, When they examine its schema, Then they see all properties with types, descriptions, validation rules, and whether fields are required or optional
  5. Given the API schemas change, When the backend code is updated with new types, Then the Swagger documentation automatically reflects the updated schemas without manual documentation updates

User Story 6 - Rate Limiting and API Quotas (Priority: P3)

API consumers need transparent rate limiting that prevents abuse while providing clear feedback about limits, current usage, and when limits reset so they can implement appropriate retry logic and stay within usage boundaries.

Why this priority: Important for system stability and preventing abuse, but not essential for initial functionality. Can be added after core API operations are stable.

Independent Test: Can be fully tested by configuring rate limits, making repeated requests to trigger limits, verifying 429 responses include rate limit headers, waiting for reset period, and confirming access is restored.

Acceptance Scenarios:

  1. Given an API consumer makes requests, When they receive responses, Then each response includes headers indicating rate limit total, remaining requests, and reset time
  2. Given an API consumer exceeds their rate limit, When they make another request, Then they receive a 429 Too Many Requests response with a Retry-After header indicating when they can retry
  3. Given different rate limits for different endpoint types, When consumers access various endpoints, Then authentication endpoints have stricter rate limits than general data endpoints
  4. Given different rate limits for authenticated vs unauthenticated requests, When consumers make requests, Then authenticated users have higher rate limits than unauthenticated access
  5. Given a rate limit reset time has passed, When a previously rate-limited consumer makes a new request, Then their rate limit counter is reset and the request is processed normally

Edge Cases

  • Concurrent token refresh: Multiple clients refresh the same token simultaneously - only first refresh succeeds, others receive 401 requiring re-authentication
  • Token tampering: Client modifies token contents - API validates signature and rejects with 401 Unauthorized
  • Malformed JSON: Request body contains invalid JSON - API returns 400 Bad Request with parsing error details
  • Missing Content-Type header: Request omits Content-Type for endpoints expecting JSON - API returns 415 Unsupported Media Type
  • Extremely large payloads: Request exceeds maximum payload size - API returns 413 Payload Too Large before processing
  • Unsupported HTTP methods: Client uses wrong HTTP method for endpoint - API returns 405 Method Not Allowed with Allow header listing supported methods
  • API version deprecation: Client accesses deprecated API version - API returns 410 Gone with migration guidance
  • Expired password reset tokens: Client attempts to use expired password reset token - API returns 400 Bad Request indicating token is expired
  • Invalid 2FA codes: Client provides wrong 2FA verification code - API returns 401 Unauthorized with remaining attempts (if applicable)
  • Scope escalation attempts: Third-party app requests token refresh with expanded scopes - API rejects and requires new authorization flow
  • Stale Swagger cache: Documentation shows outdated schemas - API serves Swagger spec with appropriate cache headers for freshness

Requirements

Functional Requirements

Authentication & Authorization (P1 - Launch)

  • FR-001: API MUST provide an authentication endpoint that accepts email and password credentials and returns access token, refresh token, token type (Bearer), and expiration timestamp
  • FR-003: API MUST provide a token refresh endpoint that accepts a valid refresh token and returns a new access token without requiring re-authentication
  • FR-004: API MUST provide a logout endpoint that revokes the provided refresh token
  • FR-005: API MUST validate access tokens on all protected endpoints by verifying signature, expiration, and user status
  • FR-006: API MUST include authentication requirements in all endpoint documentation indicating whether authentication is required, optional, or not needed
  • FR-007: API MUST provide a password reset initiation endpoint that sends a time-limited reset token via email
  • FR-008: API MUST provide a password reset completion endpoint that validates the reset token and updates the user's password

Passwordless Authentication (P2)

  • FR-002: API MUST provide a passwordless authentication endpoint that initiates email verification and returns authentication tokens upon successful verification code validation

Third-Party OAuth & Advanced Security (P3)

  • FR-009: API MUST provide OAuth authorization endpoints for third-party applications including authorization initiation, user consent, code exchange, and token refresh
  • FR-010: API MUST enforce scope-based access control on all endpoints, rejecting requests that exceed granted scopes with appropriate error responses
  • FR-011: API MUST provide endpoints for 2FA setup (authenticator app enrollment) and 2FA verification code validation
  • FR-012: API MUST challenge requests to 2FA-protected scopes with 2FA verification requirements

Error Handling & Validation

  • FR-013: API MUST return HTTP status code 400 Bad Request for validation errors with response body containing structured error details listing each validation failure
  • FR-014: API MUST return HTTP status code 401 Unauthorized when authentication is required but not provided or invalid
  • FR-015: API MUST return HTTP status code 403 Forbidden when authenticated user lacks required permissions or scopes
  • FR-016: API MUST return HTTP status code 404 Not Found when requested resource doesn't exist
  • FR-017: API MUST return HTTP status code 429 Too Many Requests when rate limits are exceeded
  • FR-018: API MUST return HTTP status code 500 Internal Server Error for unhandled server errors while logging detailed error information securely
  • FR-019: API MUST return HTTP status code 503 Service Unavailable when system is under maintenance or temporarily unavailable
  • FR-020: API MUST validate all request input data including required fields, data types, format constraints, and business rules before processing
  • FR-021: API MUST return validation error responses in consistent structure with field name, validation rule violated, and user-friendly error message
  • FR-022: API MUST sanitize error messages in production to prevent leaking sensitive system information while providing sufficient detail for debugging
  • FR-023: API MUST include correlation IDs in error responses to enable error tracking and debugging across distributed systems

Request/Response Standards

  • FR-024: API MUST accept and return JSON-formatted data with Content-Type application/json
  • FR-025: API MUST use standard HTTP methods consistently: GET for retrieval, POST for creation, PUT for full updates, PATCH for partial updates, DELETE for removal
  • FR-026: API MUST return appropriate success status codes: 200 OK for successful retrieval/update, 201 Created for successful creation with Location header, 204 No Content for successful deletion
  • FR-027: API MUST support pagination for list endpoints with query parameters for page number/cursor and page size
  • FR-028: API MUST include pagination metadata in list responses showing total count, current page, total pages, and links to next/previous pages
  • FR-029: API MUST support filtering on list endpoints using query parameters that map to resource attributes
  • FR-030: API MUST support sorting on list endpoints with query parameters specifying sort field and direction (ascending/descending)
  • FR-031: API MUST accept date/time values in ISO 8601 format and return date/time values in ISO 8601 format with timezone information
  • FR-032: API MUST use consistent field naming conventions in JSON responses (camelCase recommended for JavaScript/TypeScript ecosystem)
  • FR-033: API MUST include appropriate cache control headers for responses to optimize client-side caching behavior

Documentation

  • FR-034: API MUST generate OpenAPI/Swagger specification automatically from NestJS type definitions and decorators
  • FR-035: API MUST serve interactive Swagger UI documentation at a dedicated endpoint accessible to developers
  • FR-036: API MUST document all endpoints with descriptions, parameters, request bodies, response schemas, status codes, and examples
  • FR-037: API MUST document authentication requirements for each endpoint including required scopes and 2FA requirements
  • FR-038: API MUST document all data models with property types, descriptions, validation rules, and required/optional indicators
  • FR-039: API MUST include example requests and responses in documentation for common use cases
  • FR-040: API MUST allow testing endpoints directly from Swagger UI with authentication token input

Rate Limiting & Performance

  • FR-041: API MUST implement configurable rate limiting on authentication endpoints to prevent brute force attacks
  • FR-042: API MUST implement rate limiting on all public endpoints to prevent abuse
  • FR-043: API MUST include rate limit information in response headers: limit total, remaining requests, and reset timestamp
  • FR-044: API MUST return 429 Too Many Requests with Retry-After header when rate limits are exceeded
  • FR-045: API MUST apply different rate limits for authenticated vs unauthenticated requests, with authenticated users receiving higher limits
  • FR-046: API MUST apply stricter rate limits to sensitive endpoints (authentication, password reset) compared to general data endpoints

Security

  • FR-047: API MUST require HTTPS for all endpoints in production environments
  • FR-048: API MUST validate Content-Type headers and reject requests with incorrect or missing Content-Type using 415 Unsupported Media Type
  • FR-049: API MUST enforce maximum request payload size limits and reject oversized requests with 413 Payload Too Large
  • FR-050: API MUST implement CORS (Cross-Origin Resource Sharing) with configurable allowed origins for frontend applications
  • FR-051: API MUST include security headers in all responses (X-Content-Type-Options, X-Frame-Options, X-XSS-Protection)
  • FR-052: API MUST log all authentication events, authorization failures, and rate limit violations for security auditing
  • FR-053: API MUST validate and sanitize all user input to prevent injection attacks
  • FR-054: API MUST implement request timeouts to prevent resource exhaustion from long-running requests

Key Entities

  • API Endpoint: Represents a specific API operation. Attributes include HTTP method, URL path, authentication requirement, required scopes, rate limit configuration, request schema, response schemas for each status code, and documentation text. Relationship to resource types and permission scopes.

  • API Response: Represents the structure of API responses. Attributes include HTTP status code, response body schema, headers (content-type, rate limits, cache control), and correlation ID for error tracking. Consistent structure across all endpoints.

  • Validation Error: Represents a structured validation failure. Attributes include field name, validation rule violated (required, type, format, range), error message, and constraint details. Used in 400 Bad Request responses.

  • Rate Limit: Represents usage quotas for API consumers. Attributes include endpoint or endpoint group, limit total (requests per time window), time window duration, current usage count, reset timestamp, and consumer identifier (user, IP address, or API client). Relationship to authenticated users and third-party API clients.

  • API Documentation Schema: Represents the OpenAPI/Swagger specification. Attributes include API version, base URL, available endpoints with full specifications, data model schemas, authentication schemes, and example requests/responses. Auto-generated from NestJS decorators and types.

Success Criteria

Measurable Outcomes

  • SC-001: Developers can authenticate with the API and receive valid tokens in under 2 seconds using any of the supported authentication methods
  • SC-002: API returns appropriate HTTP status codes (4xx for client errors, 5xx for server errors) with structured error responses for 100% of error conditions
  • SC-003: API documentation (Swagger UI) automatically reflects all endpoints and schemas without manual updates when backend types change
  • SC-004: API handles validation errors consistently, returning detailed field-level errors that enable frontend applications to display targeted error messages to users
  • SC-005: Rate limiting prevents brute force attacks by limiting authentication endpoint requests while providing clear feedback to legitimate users about limits and reset times
  • SC-006: Third-party developers can complete OAuth integration and make successful scoped API requests following documentation alone, without requiring additional support
  • SC-007: API responds to authenticated requests within 500 milliseconds under normal load (excluding external integrations and database queries)
  • SC-008: API maintains 99.9% uptime for all endpoints (excluding planned maintenance windows)
  • SC-009: Developers report that API error messages provide sufficient information to resolve issues without examining server logs (measured through developer surveys or support ticket reduction)
  • SC-010: Zero authentication token compromise incidents due to proper HTTPS enforcement, secure token generation, and HttpOnly cookie usage