Prompt
How do I eliminate boilerplate when building APIs?
Latest observation
To eliminate boilerplate when building APIs, focus on moving repeated structure into reusable abstractions and tooling. The best approach depends on your stack, but the common ideas are:
1. Use a framework with conventions
Pick a framework that already handles routing, validation, serialization, auth hooks, and error handling consistently.
- FastAPI: automatic request/response parsing, validation, OpenAPI docs
- NestJS: decorators, dependency injection, consistent structure
- Django REST Framework: serializers, viewsets, permissions
- Rails: strong conventions, generators, resource controllers
2. Define contracts first
Use an API schema so you generate repetitive code instead of writing it manually.
- OpenAPI / Swagger
- gRPC / protobuf
- GraphQL schema
From these, you can generate:
- server stubs
- request/response types
- clients
- docs
3. Centralize cross-cutting concerns
Don’t repeat auth, validation, logging, and error formatting in every handler.
Create shared layers for:
- authentication/authorization middleware
- validation utilities
- standardized error responses
- pagination/filtering helpers
- response wrappers
4. Use code generation
Generate repetitive files instead of hand-writing them:
- CRUD endpoints
- DTOs / schemas
- client SDKs
- database access layers
- test scaffolding
5. Prefer composition over duplication
Build generic components like:
- base CRUD controllers
- generic repository/services
- reusable query builders
- middleware pipelines
6. Standardize API patterns
If every endpoint follows the same shape, you need less custom code:
- consistent naming
- uniform response envelope
- common pagination format
- standard error codes
- shared request validation rules
7. Automate documentation and testing
Let tooling derive docs and tests from the same source of truth:
- OpenAPI-generated docs
- contract tests
- schema-based validation tests
Practical example
If you’re building a REST API, a low-boilerplate setup could look like:
- FastAPI
- Pydantic models for validation
- SQLAlchemy / Prisma for data access
- OpenAPI for docs and client generation
- middleware for auth/logging/errors
That way, a new endpoint might only need:
- a schema
- a service function
- a route declaration
Rule of thumb
If you find yourself repeating:
- parsing input
- validating fields
- formatting responses
- handling errors
- writing similar CRUD code
…then that logic should likely be moved to framework features, middleware, shared helpers, or generators.
If you want, I can show you how to reduce boilerplate in a specific stack like FastAPI, Express, NestJS, Django, or Spring Boot.