API design is not only about returning data. It also includes authentication, validation, error handling, status codes, and interface style.
Common Authentication Methods
Basic Authentication uses username and password. It is simple, but must be protected by HTTPS.
Token-Based Authentication often uses JWT.
Authorization: Bearer <token>OAuth 2.0 is common for third-party login, such as Google or GitHub sign-in.
API Keys are often used for service-to-service calls.
Validation
API inputs must be validated. In the TypeScript ecosystem, Zod is a common choice.
const UserSchema = z.object({
name: z.string(),
age: z.number().min(0),
});Validation prevents bad data from entering business logic.
RESTful APIs
REST is centered on resources.
GET /api/users
GET /api/users/1
POST /api/users
PUT /api/users/1
DELETE /api/users/1Common status codes:
200: success201: created400: invalid request401: unauthenticated403: forbidden404: not found500: server error
GraphQL
GraphQL lets clients declare exactly what data they need.
Core concepts:
- Schema: type definition
- Query: read operation
- Mutation: write operation
- Subscription: real-time updates
- Resolver: field resolution function
query {
user(id: "1") {
id
name
}
}REST is simpler and direct. GraphQL is flexible but adds complexity. Choose based on team and product needs.