API Design for Microservices

Introduction

APIs are the contracts between your services. Through designing APIs for systems handling millions of requests, I've learned that good API design isn't just about following REST conventionsβ€”it's about creating intuitive, evolvable interfaces that teams can depend on for years.

This article covers practical API design principles, versioning strategies, and how to use OpenAPI with FastAPI for contract-first development.

API Design Principles

REST Fundamentals

REST (Representational State Transfer) provides a consistent way to design APIs around resources.

spinner

Resource Naming

# βœ… Good: Nouns for resources, plural forms
GET    /users              # List users
GET    /users/{id}         # Get specific user
POST   /users              # Create user
PUT    /users/{id}         # Replace user
PATCH  /users/{id}         # Partial update
DELETE /users/{id}         # Delete user

# βœ… Good: Nested resources for relationships
GET    /users/{id}/orders           # User's orders
GET    /orders/{id}/items           # Order's items
POST   /users/{id}/addresses        # Add address to user

# ❌ Bad: Verbs in URLs (RPC-style)
POST   /getUser
POST   /createUser
POST   /deleteUser
GET    /fetchAllOrders

HTTP Methods and Status Codes

Status Code Reference

Code
Meaning
When to Use

200

OK

Successful GET, PUT, PATCH

201

Created

Successful POST

204

No Content

Successful DELETE

400

Bad Request

Invalid input

401

Unauthorized

Missing/invalid authentication

403

Forbidden

Valid auth but insufficient permissions

404

Not Found

Resource doesn't exist

409

Conflict

Resource state conflict

422

Unprocessable Entity

Validation error

500

Internal Server Error

Unexpected server error

503

Service Unavailable

Temporary unavailability

Request and Response Design

Consistent Response Format

Error Handling

API Versioning Strategies

URL Path Versioning

Header-Based Versioning

Versioning Best Practices

Contract-First Design with OpenAPI

Defining the Contract First

Implementing from Contract

Consumer-Driven Contract Testing

API Documentation

Practical Exercise

Exercise: Design an Order API

Design a complete API for an order service:

Key Takeaways

  1. Use resources, not actions - Design around nouns, use HTTP methods for verbs

  2. Be consistent - Same patterns across all endpoints

  3. Version from day one - Plan for breaking changes

  4. Contract-first - Define OpenAPI spec before implementation

  5. Document thoroughly - Good docs reduce support burden

What's Next?

With well-designed APIs, we need to understand how services communicate. In Article 4: Synchronous Communication, we'll cover HTTP/REST patterns, gRPC, and service discovery.


This article is part of the Microservice Architecture 101 series.

Last updated