How to Design Your First API
When people write their first API, they often focus on whether it can return data. If the frontend can call it and the page can display something, the API feels done.
But an API is not a temporary function. It is a contract between frontend, backend, database, permissions, error handling, and future extension. If the first design is too casual, every later change creates ripple effects.
Your first API does not need to be complex, but it must be clear, stable, and understandable.
First Define the User Action
Before writing a URL, define the user action.
Is the user creating a project, fetching a list, updating settings, uploading a file, submitting an order, or viewing a result? An API should serve one clear action. Do not put unrelated actions into one endpoint.
For example, “create project” and “update project settings” should be separate APIs. “Get project list” and “get project detail” should also be separate.
The clearer the API, the easier it is for the frontend to use, for the backend to maintain, and for issues to be debugged.
Organize Paths by Resources, Not Verbs
A common beginner style is:
/api/createProject
/api/getProjectList
/api/updateProject
/api/deleteProject
This works, but it becomes messy over time. A better pattern uses resource paths plus HTTP methods:
GET /api/projects
POST /api/projects
GET /api/projects/:id
PATCH /api/projects/:id
DELETE /api/projects/:id
The path represents the resource, and the method represents the action. This makes the API structure consistent and easier to understand.
Put Parameters in the Right Place
API parameters usually belong in three places: path parameters, query parameters, and request body.
Path parameters identify a resource, such as 123 in /api/projects/123. Query parameters control filtering, search, sorting, and pagination, such as ?status=active&page=1. The request body submits data for creation or update.
Do not put all parameters into the body, and do not put complex data into the URL.
A simple rule: resource identity goes in the path, list controls go in the query, submitted data goes in the body.
Keep Response Structure Stable
The data structure returned to the frontend should be stable. Do not return an array today and an object tomorrow. Do not use completely unrelated structures for success and failure.
A common success response:
{
"data": {
"id": "project_123",
"name": "Demo Project",
"status": "active"
}
}
A list response can include pagination:
{
"data": [
{ "id": "project_123", "name": "Demo Project" }
],
"pagination": {
"page": 1,
"pageSize": 20,
"total": 128
}
}
Stable response structures reduce special-case logic on the frontend.
Make Error Responses Useful
When an API fails, do not only return “failed” or “server error.”
An error response should include an error code, readable message, and field information when useful:
{
"error": {
"code": "PROJECT_NAME_REQUIRED",
"message": "Project name is required.",
"field": "name"
}
}
The frontend can use code for logic, message for display, and field to highlight a form input.
Good error design helps developers and improves user experience.
Validate Input
Never trust data from the frontend.
Even if the frontend already limits field length, format, and required fields, the backend must validate again. APIs can be called directly, bypassing the frontend.
Validation should include required fields, types, length limits, enum values, number ranges, file size, permission scope, and business rules.
The earlier and clearer validation is, the less polluted your data becomes.
Separate Authentication and Authorization
Authentication answers “who are you?” Authorization answers “are you allowed to do this?”
Many beginners only check whether the user is logged in, but forget to check whether the user can operate on a specific resource.
A logged-in user should not be able to delete someone else's project. A team member may view a project but not edit billing. A normal user may upload files but not access admin endpoints.
Every API involving user data should consider both authentication and authorization.
Consider Idempotency
Idempotency means running the same request multiple times does not create unexpected side effects.
If a user clicks “save settings” twice, it should not create two settings. If a payment webhook arrives twice, it should not create two orders. If the same resource is deleted twice, the system should not break.
Not every API is naturally idempotent, but important APIs should be designed with this in mind.
Payment, orders, webhooks, background tasks, and batch operations especially need duplicate-request handling.
Support Pagination From the Start
Do not let list APIs return all data at once.
When data is small, it looks fine. When data grows, the API slows down, the page freezes, and database pressure increases.
List APIs should support pagination, sorting, and necessary filters from the beginning. Even if there are only a few items now, keep the structure.
Example:
GET /api/projects?page=1&pageSize=20&status=active&sort=createdAt_desc
This makes future growth much easier.
Do Not Overdesign Versioning Too Early
Some people design /api/v1, /api/v2, and complex versioning strategies for their first API.
If the API only serves your own frontend, early complex versioning may not be necessary. It is more important to keep response structures stable and avoid casually breaking field meanings.
If your API will be public, or used by multiple long-term clients, you need more serious versioning, compatibility, and deprecation strategies.
Versioning is not more professional just because it appears earlier. It depends on API boundaries.
Write Documentation With the API
API documentation does not need to be fancy at first, but it should explain what the API does, request parameters, response shape, errors, and permission requirements.
A simple document can be:
POST /api/projects
Purpose: Create project
Permission: Logged-in user
Body: name, description
Success: Return project detail
Errors: PROJECT_NAME_REQUIRED, PROJECT_LIMIT_EXCEEDED
The value of documentation is not formality. It reduces communication cost. Six months later, you will thank yourself.
A First API Template
Use this template before writing an endpoint:
API name:
User action:
Resource:
HTTP method:
Path:
Path params:
Query params:
Request body:
Permission requirement:
Success response:
Error response:
Needs idempotency:
Needs pagination:
Needs logging:
Filling this out before coding prevents many casual design mistakes.
Final Thoughts
The goal of your first API is not to show off. It is to create a stable contract.
Clear paths, clear parameters, stable responses, readable errors, explicit permissions, and synchronized documentation make every later feature easier to build.
Next, we continue with APIs and external systems: Webhook in Practice.
评论
0分享你对这一章的想法