Design and implement a production-grade REST API: resource modeling, versioning, authN/authZ, pagination, rate limiting, error handling, observability, and test strategy. Provide runnable code, tests, and deployment steps.
Assistant
The user wants a "production-grade REST API" design and implementation.
The scope is broad:
Resource Modeling: Define entities and relationships.
Versioning: Strategy for API evolution.
AuthN/AuthZ: Authentication (who are you) and Authorization (what can you do).
Pagination: Handling large datasets.
Rate Limiting: Protecting the API.
Error Handling: Standardized failure responses.
Observability: Logging, metrics, tracing.
Test Strategy: Unit, integration, E2E.
Runnable Code: A working example.
Deployment Steps: How to ship it.
Technology Stack Selection:
To make this "runnable" and modern, I should choose a popular, robust stack.
Language: Go (Golang). It's the standard for backend microservices due to performance, concurrency, and strict typing. Python (FastAPI) or Node (Express/NestJS) are also good, but Go is often preferred for "production-grade" system examples because of its explicit error handling and standard library strength. Let's stick with Go using the Gin framework (popular, fast) or standard library (net/http). Gin offers a good balance of speed and middleware support for the requested features (rate limiting, auth). Let's use Gin.
Database:PostgreSQL. The industry standard for relational data.
Scenario: A "Task Management" API (Todo list on steroids). It's complex enough to show relationships (Users, Projects, Tasks) but simple enough to fit in one response.
Resource Modeling:
User: ID, Email, Password (hashed), Role.
Project: ID, Name, OwnerID.
Task: ID, Title, Status, ProjectID, AssigneeID.
Versioning: URL versioning (e.g., /api/v1/) is the most pragmatic and widely understood approach for a standalone demo.
AuthN/AuthZ:
AuthN: JWT (JSON Web Tokens).
AuthZ: RBAC (Role-Based Access Control) or simple ownership checks.
Pagination: Offset-based (page & per_page) or Cursor-based. Offset is easier to demonstrate for a general example, though cursor is better for infinite scroll. Let's do Offset with metadata (TotalPages, CurrentPage).
Rate Limiting: Token Bucket algorithm. In Go, uber-go/rate or a middleware like gin-limiter (using Redis usually). For a standalone runnable demo, an in-memory rate limiter is easier to run without external deps, but I should mention Redis for production. Let's use a simple in-memory limiter for the code to ensure it runs without a Docker Compose setup of 5 services.
Tracing is hard to demo without a collector (Jaeger), so I'll focus on Request ID propagation.
Test Strategy:
Unit tests for business logic (mocking DB).
Integration tests for API endpoints (httptest).
Drafting the Code Structure:
main.go: Entry point, wiring dependencies.
config/: Env vars.
models/: Structs.
storage/: DB interface (mock + real implementation).
handlers/: HTTP handlers.
middleware/: Auth, Rate Limiting, Logging.
docs/: OpenAPI spec (maybe just describe it).
Refining the "Runnable" aspect:
Setting up a real Postgres DB makes "runnability" hard for a user just copy-pasting. I will use SQLite (via gorm or sqlx driver) for the code so it works out-of-the-box, but write the code such that it looks like Postgres logic (standard SQL). Actually, for "production grade", we usually abstract the DB. I will provide a MockStore for immediate execution and the interface for a real SQL implementation.
Key constraints/Features to hit specifically:
Production Grade: Graceful shutdown, config management, structured logging.
Deployment: Dockerfile + Docker Compose.
Step-by-Step Implementation Plan:
Design: Define the OpenAPI-style resources.
Setup: Go mod init.
Core Logic: Structs and Interfaces.
Implementation: Handlers & DB logic (using an in-memory map for the code snippet to be runnable without Docker, but structured for SQL).
Correction: A real "production grade" example should really use a DB. I will provide the Docker Compose setup.
Middleware: Auth (JWT), Rate Limiting, Logging.
Testing: Example *_test.go.
Self-Correction during drafting:
Writing a full production backend in one LLM response is too long. I need to provide a "Vertical Slice". I will implement the Task resource fully (Create, List with pagination) and touch on the others. I will focus on the infrastructure code (middleware, error handling) as that's what makes it "production grade".
Let's choose Go (Gin) + SQLite (for portability in the snippet, but easy to swap to Postgres) + JWT.
Let's write the code mentally to ensure imports are correct. github.com/gin-gonic/gin, github.com/golang-jwt/jwt/v5.
Final Polish:
Ensure the code is copy-pasteable into a single directory for the immediate "runnable" part, but explain how to split it. I will provide a docker-compose for the full production stack.
Constraint Checklist & Confidence Score:
Resource modeling? Yes (User/Task).
Versioning? Yes (/v1/).
AuthN/AuthZ? Yes (JWT).
Pagination? Yes.
Rate Limiting? Yes.
Error Handling? Yes.
Observability? Yes (Logging/Metrics).
Test strategy? Yes.
Runnable code? Yes.
Deployment steps? Yes.
Confidence Score: 5/5
Mental Sandbox Simulation:
User copies code.
User runs go mod init api.
User runs go mod tidy.
User runs go run main.go.
User curls localhost:8080/v1/health. -> 200 OK.
User curls localhost:8080/v1/login. -> gets token.
User curls localhost:8080/v1/tasks with token. -> 200 OK.
User hits rate limit. -> 429.
This flow works. I will structure the response to guide them through this.
This guide designs and implements a production-grade REST API using Go (Golang) with the Gin framework. This stack is chosen for its performance, type safety, and extensive ecosystem suitable for high-throughput production environments.
We will build a Task Management API.
1. Architecture & Design Decisions
Resource Modeling: User (1) to Task (N).
Versioning: URL Path Versioning (e.g., /api/v1/).
AuthN/AuthZ: JWT (JSON Web Tokens) with Role-Based Access Control (RBAC).
Pagination: Offset/Limit based via query parameters.
mkdir api-server && cd api-server
go mod init github.com/you/api-server
go get -u github.com/gin-gonic/gin github.com/golang-jwt/jwt/v5 golang.org/x/time/rate
A. Configuration & Models (models/models.go)
go
package models
import "time"
type Role string
const (
RoleAdmin Role = "admin"
RoleUser Role = "user"
)
type User struct {
ID string `json:"id"`
Email string `json:"email"`
Password string `json:"-"` // Never return password
Role Role `json:"role"`
}
type Task struct {
ID string `json:"id"`
Title string `json:"title" binding:"required"`
Description string `json:"description"`
Status string `json:"status"` // e.g., "pending", "done"
OwnerID string `json:"owner_id"`
CreatedAt time.Time `json:"created_at"`
}
// Pagination Wrapper
type PaginatedResponse struct {
Data interface{} `json:"data"`
Page int `json:"page"`
Limit int `json:"limit"`
TotalItems int64 `json:"total_items"`
}
B. Repositories (Data Access) (repositories/task_repo.go)
For this runnable example, we use an in-memory thread-safe map. In production, you would replace this with sql.DB logic for Postgres.
go
package repositories
import (
"sync"
"github.com/you/api-server/models"
)
type TaskRepository interface {
Create(task *models.Task) error
GetByID(id string) (*models.Task, error)
List(userID string, page, limit int) ([]models.Task, int64, error)
}
type InMemoryTaskRepo struct {
store sync.Map
}
func NewInMemoryTaskRepo() *InMemoryTaskRepo {
return &InMemoryTaskRepo{}
}
func (r *InMemoryTaskRepo) Create(task *models.Task) error {
r.store.Store(task.ID, task)
return nil
}
func (r *InMemoryTaskRepo) GetByID(id string) (*models.Task, error) {
val, ok := r.store.Load(id)
if !ok {
return nil, nil
}
return val.(*models.Task), nil
}
// List handles pagination logic in-memory (simplified)
func (r *InMemoryTaskRepo) List(userID string, page, limit int) ([]models.Task, int64, error) {
var tasks []models.Task
var total int64
// 1. Filter and Collect
r.store.Range(func(key, value interface{}) bool {
t := value.(*models.Task)
if t.OwnerID == userID {
tasks = append(tasks, *t)
}
return true
})
total = int64(len(tasks))
// 2. Pagination (Slicing)
start := (page - 1) * limit
if start > int(total) {
return []models.Task{}, total, nil
}
end := start + limit
if end > int(total) {
end = int(total)
}
return tasks[start:end], total, nil
}
C. Middlewares (middlewares/auth.go, rate_limit.go)
# Build stage
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY go.mod ./
COPY go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o main .
# Final stage
FROM alpine:latest
WORKDIR /root/
COPY --from=builder /app/main .
EXPOSE 8080
CMD ["./main"]