DEV Community

Cover image for API Design Interview Questions: REST and Beyond
Matt Frank
Matt Frank

Posted on

API Design Interview Questions: REST and Beyond

API Design Interview Questions: REST and Beyond

Picture this: you're in a system design interview, and the interviewer asks you to design an API for a social media platform. Your mind races through countless decisions – how do you model user relationships? What about pagination for infinite scroll? How do you handle different mobile app versions?

API design questions are among the most common in technical interviews because they reveal how you think about scalability, user experience, and system architecture. Unlike pure algorithms questions, API design showcases your ability to build systems that real users depend on. Whether you're designing Instagram's feed API or Stripe's payment processing endpoints, the same fundamental principles apply.

In this article, we'll explore the key concepts that interviewers look for when evaluating API design skills, focusing on resource modeling, versioning strategies, pagination approaches, and error handling patterns. By the end, you'll have a framework for approaching any API design question with confidence.

Core Concepts: The Building Blocks of Great APIs

Resource Modeling: Thinking in Resources, Not Functions

The foundation of REST API design lies in identifying and modeling resources correctly. A resource represents any information that can be named and addressed through a URI. Think of resources as the nouns in your system, while HTTP methods represent the verbs.

Consider a blogging platform. Your core resources might include:

  • Users: Representing authors and readers
  • Posts: Individual blog entries with content and metadata
  • Comments: User responses to posts
  • Categories: Ways to organize and filter content
  • Subscriptions: Relationships between users and content

Each resource should have a clear, hierarchical structure that reflects real-world relationships. Users create posts, posts belong to categories, and comments belong to posts. This hierarchy becomes your URL structure: /users/123/posts for a user's posts, or /posts/456/comments for a post's comments.

The key insight is that good resource modeling makes your API intuitive. Developers should be able to guess endpoint URLs based on the relationships they understand from your domain.

API Versioning: Managing Change Over Time

APIs evolve, but existing clients can't break. This creates one of the most challenging aspects of API design: how do you introduce new features while maintaining backward compatibility?

There are several versioning strategies, each with distinct trade-offs:

URL Versioning places the version directly in the path: /v1/users vs /v2/users. This approach is explicit and easy to understand, making it popular for public APIs. You can visualize how different versions route to different service layers using InfraSketch, which helps clarify the architectural implications.

Header Versioning uses custom headers like API-Version: 2.0. This keeps URLs clean and allows more granular version control per endpoint. However, it's less visible to developers and harder to cache effectively.

Content Negotiation leverages the Accept header: Accept: application/vnd.api.v2+json. This follows HTTP standards but can become complex as you add multiple content types and versions.

The architectural challenge is routing requests to the appropriate service version while sharing common infrastructure like authentication, rate limiting, and monitoring.

Pagination: Handling Large Data Sets

Real-world APIs serve massive datasets. Instagram has billions of photos, GitHub has millions of repositories, and your API needs to handle large collections efficiently.

Offset-based Pagination uses ?limit=20&offset=100 parameters. It's intuitive and allows jumping to arbitrary pages, but performance degrades with large offsets as databases must skip increasing numbers of records.

Cursor-based Pagination uses opaque tokens that represent positions in the dataset: ?limit=20&cursor=eyJpZCI6MTIzfQ. This approach provides consistent performance regardless of dataset size and handles real-time updates gracefully, but you lose the ability to jump to arbitrary pages.

Time-based Pagination works well for chronological data: ?limit=20&since=2023-12-01T10:00:00Z. Social media feeds often use this pattern because users care about recent content, not historical browsing.

The architectural consideration is how your API servers coordinate with databases and caches to maintain pagination state while serving consistent results across distributed systems.

Error Handling: Communicating Problems Clearly

Robust error handling separates professional APIs from amateur ones. Errors aren't just about HTTP status codes – they're about providing actionable information that helps developers solve problems quickly.

Your error architecture should distinguish between different error types:

Client Errors (4xx) indicate problems with the request itself. A 400 Bad Request should include specific validation messages, while 401 Unauthorized should guide users toward authentication. Rate limiting deserves special attention – 429 Too Many Requests should include retry timing information.

Server Errors (5xx) represent infrastructure problems. These errors should be logged extensively for your monitoring systems while providing minimal information to clients for security reasons.

Business Logic Errors require custom handling. When a payment fails or inventory runs out, you need domain-specific error codes and messages that client applications can handle programmatically.

Error responses should follow a consistent structure across your entire API, making client-side error handling predictable and reducing integration complexity.

How It Works: Request Flow and System Interactions

Understanding API design requires seeing how requests flow through your system architecture. Let's trace a typical API request from client to database and back.

Request Processing Pipeline

When a client makes an API request, it enters a processing pipeline with multiple stages. Each stage has specific responsibilities and can be scaled independently.

Load Balancers receive incoming requests and distribute them across multiple API server instances. They perform health checks and can route different API versions to different server clusters.

API Gateway handles cross-cutting concerns like authentication, rate limiting, request logging, and response transformation. This is where API keys get validated and usage quotas get enforced.

Application Servers contain your business logic and resource modeling. They parse requests, validate data, apply business rules, and coordinate with downstream services.

Data Layer includes databases, caches, and external services. Modern APIs often need to aggregate data from multiple sources before forming responses.

Tools like InfraSketch help you visualize these pipeline stages and understand how components interact, especially when designing for high availability and horizontal scaling.

Resource Resolution and Data Aggregation

Complex API endpoints often require data from multiple sources. Consider an endpoint like /users/123/dashboard that returns a personalized view combining user profile, recent activity, recommendations, and notifications.

The API server must coordinate multiple database queries, cache lookups, and potentially external service calls. This coordination can happen serially (slower but simpler) or in parallel (faster but more complex error handling).

Caching strategies become critical at this stage. You might cache user profiles for minutes, activity feeds for seconds, and recommendations for hours. Each resource type has different consistency requirements and update patterns.

Response Assembly and Formatting

Once your API server has gathered the necessary data, it must format responses according to your resource model. This includes selecting appropriate fields based on client permissions, applying data transformations, and generating pagination metadata.

Response formatting often involves trade-offs between payload size and client complexity. Including related resources inline (like post comments) reduces round trips but increases bandwidth usage. Providing resource links instead requires more requests but enables better caching.

Design Considerations: Trade-offs and Scaling Strategies

Performance vs. Flexibility

API design constantly balances performance against flexibility. Highly specific endpoints like /users/123/recent-posts-with-comments perform well because they're optimized for specific use cases. However, they create maintenance overhead and don't adapt well to changing client needs.

Generic endpoints like /posts?user=123&include=comments provide flexibility but require more complex query processing and caching strategies. The architecture must support dynamic field selection, filtering, and sorting while maintaining acceptable performance.

GraphQL represents one approach to this trade-off, allowing clients to specify exactly what data they need. However, it introduces new complexities around query optimization and security.

Consistency vs. Availability

Distributed API architectures must handle the CAP theorem's constraints. When user data is spread across multiple database shards or geographic regions, you must choose between immediate consistency and high availability.

Eventually consistent systems can serve stale data but remain available during network partitions. Strongly consistent systems always serve current data but may become unavailable during failures.

Your API design should make these trade-offs explicit through documentation and potentially through query parameters that let clients choose their consistency level for different use cases.

Security and Access Control

Modern APIs serve multiple client types with different permission levels. Your mobile app might access user data directly, while third-party integrations use more restrictive scopes.

Resource-based access control ties permissions to specific resources and operations. A user might have read access to public posts but write access only to their own content. This granularity requires careful architecture to avoid performance bottlenecks from permission checks.

API keys, OAuth tokens, and JWT credentials each serve different use cases and have distinct architectural implications for token validation and revocation.

Key Takeaways

Successful API design in interviews demonstrates your ability to think systematically about complex distributed systems. Focus on these core principles:

Resource modeling should reflect real-world domain concepts and relationships. Start with nouns (resources) and use HTTP verbs for actions. Your URL structure should be intuitive and hierarchical.

Versioning strategy depends on your client ecosystem and change frequency. URL versioning works well for public APIs, while header versioning suits internal APIs with sophisticated clients.

Pagination approach should match your data access patterns. Use offset pagination for browsable datasets, cursor pagination for infinite scroll, and time-based pagination for activity feeds.

Error handling needs to be comprehensive and actionable. Distinguish between client errors, server errors, and business logic failures. Provide enough information for debugging without exposing security vulnerabilities.

System architecture should separate concerns cleanly. API gateways handle cross-cutting concerns, application servers implement business logic, and data layers manage persistence and caching.

When discussing these concepts in interviews, always consider scaling implications. How does your design handle 10x more traffic? What about 100x more data? How do you maintain consistency across geographic regions?

Remember that API design is ultimately about creating interfaces that developers love to use. The best technical architecture means nothing if the developer experience is poor.

Try It Yourself

The best way to master API design is through practice. Try designing APIs for different domains: e-commerce platforms, messaging systems, file storage services, or social networks. Each domain has unique challenges that will deepen your understanding.

Start by identifying core resources and their relationships. Map out the request flow from client to database. Consider how you'll handle growth, failures, and evolving requirements.

Head over to InfraSketch and describe your API architecture in plain English. In seconds, you'll have a professional architecture diagram, complete with a design document. No drawing skills required. Use it to visualize how your API gateway connects to application servers, how data flows between services, and where you'll place caches and load balancers.

The visual representation will help you spot architectural gaps and explain your design decisions clearly during interviews. Great API design isn't just about following REST principles, it's about building systems that scale gracefully and provide excellent developer experiences.

Top comments (0)