API vs. Web API: From Interface Contracts to the Full Request Lifecycle

    This article explains what an API is and how a Web API works over HTTP. It clarifies the difference between an interface and an API, breaks down the core elements of Web APIs (URLs, HTTP methods, and status codes), and walks through the six stages of a request from client to server and back. It also covers practical contract design principles such as defining the contract first, structuring errors, versioning, idempotency, security, and observability.

    1. The Starting Point: Why You Need a “Middle Man”

    Picture a simple scenario: you own the frontend and need to display user profiles. The data lives in a backend database, but the browser cannot and should not hold the database address or credentials. There are three reasons for this:

    • Security boundary: Once credentials are shipped to the client, they are effectively exposed to every visitor.
    • Responsibility boundary: The frontend focuses on presentation and interaction, while the backend focuses on data consistency and business rules.
    • Coupling boundary: If the frontend connects directly to storage, any change to the storage structure triggers a full-stack rework.

    So the backend does something critical: it packages its capabilities and exposes only a single controlled entry point. The caller submits a user identifier, and the entry point returns that user’s profile. Whether the request goes to the primary or a read replica, whether it hits a cache, or how many copies of the data exist is something the caller neither sees nor needs to see.

    This “agreed-upon entry point” is an API (Application Programming Interface). Its essence is a collaboration contract between two programs: one side sends requests according to a specification, and the other returns results according to the same specification. The value of the contract lies in information hiding—the implementation can be replaced while the contract stays stable.

    One commonly confused distinction is worth clarifying: an interface is the concrete “opening” that gets implemented—the actual code and routes; an API is the general term for this kind of mechanism, emphasizing the contract and abstraction. The former is an instance; the latter is a category.

    2. Web API: Running the Contract Over HTTP

    A Web API is an API that uses the HTTP protocol as its communication basis—the kind of interface the frontend calls through a request library or native request capabilities. It has become mainstream because HTTP offers three engineering advantages: it is text-based, stateless, and backed by mature, general-purpose infrastructure (proxies, gateways, logging, and monitoring can all be reused directly).

    Three basic elements of a Web API:

    1. The URL as the address, used to locate a resource, for example GET /api/users/123.
    2. HTTP methods express intent: GET for queries, POST for creation, PUT for full updates, PATCH for partial updates, and DELETE for deletion.
    3. HTTP status codes express the result: 2xx for success, 3xx for redirects, 4xx for caller-side problems (such as 400 bad request, 401 unauthenticated, 403 forbidden, 404 not found), and 5xx for server-side problems (such as 500 internal error, 502/503 upstream unavailable).

    Methods and status codes together form what the industry commonly calls the RESTful style. It is worth stressing that REST is an architectural constraint and a conventional way of writing, not a mandatory standard. Keeping consistency within a team and clear semantics matters more than mechanically applying rules.

    A comparison example of semantic design:

    1. # Recommended: resource nouns + methods to express intent
    2. GET /api/users/123 # query
    3. PUT /api/users/123 # full update
    4. PATCH /api/users/123 # partial update
    5. DELETE /api/users/123 # delete
    6. POST /api/users # create
    7. # Not recommended: verbs piled into the URL
    8. GET /api/getUserById?id=123
    9. POST /api/deleteUser

    3. The Full Path of a Single Call: The Two Ends of a Black Box

    What frontend developers truly need to master are only the two ends, but understanding the middle helps with troubleshooting.

    1. Initiate the request: The client sends the call with a method, URL, headers, and query parameters or a request body.
    2. Network transmission: The request travels across the network to the server, possibly passing through a gateway and load balancer.
    3. Route dispatch: The server matches the URL and method to a handler function.
    4. Business processing: The handler completes authentication, parameter validation, storage queries, business computation, and data assembly.
    5. Serialize the response: The result is packaged as JSON and returned with a status code and response headers.
    6. Client consumption: The frontend parses the data and renders it, or branches into error handling based on the status code.

    Illustrative client code:

    1. async function loadUser(userId) {
    2. const res = await fetch(`/api/users/${encodeURIComponent(userId)}`, {
    3. method: 'GET',
    4. headers: { 'Accept': 'application/json' }
    5. });
    6. if (!res.ok) {
    7. // Both 4xx and 5xx land here; branch handling by status code
    8. throw new Error(`Request failed with status code: ${res.status}`);
    9. }
    10. return res.json();
    11. }

    Server-side pseudocode, highlighting “stable contract, replaceable implementation”:

    1. route("GET", "/api/users/{id}", handler):
    2. user = service.findById(id) # internal implementation: cache / primary-replica / multiple copies
    3. if user is null: return 404
    4. return 200, toJson(user)

    4. Practical Points for Contract Design

    • Define the contract before writing the implementation: Clarify resources, methods, status codes, and error structures so frontend and backend can develop in parallel.
    • Structure error responses: Return a consistent error code, human-readable message, and trace identifier to make problems easier to locate.
    • Versioning strategy: Reflect the version in the path or headers to avoid breaking changes affecting existing callers.
    • Idempotency awareness: GET/PUT/DELETE are naturally idempotent, while POST needs a business-level unique key to prevent duplicate submissions.
    • Security on by default: Authentication, authorization, input validation, rate limiting, and transport encryption are baseline capabilities and should not be deferred.
    • Observability: Structured logs, metrics, and alerts covering status code distribution and latency allow problems to be detected early.

    When deployed in the cloud, these capabilities are typically provided by general-purpose categories: a gateway serves as the unified entry point and handles rate limiting, a load balancer distributes traffic, a container platform hosts service instances, object storage holds static assets, a message queue enables asynchronous decoupling, and logging plus monitoring and alerting ensure observability. When choosing the corresponding categories from Baidu AI Cloud or any cloud provider, the criterion is the same: does it keep the contract simple and let the implementation evolve freely?

    5. Conclusion

    The core of an API is the contract and information hiding, and a Web API is the concrete form of that contract running over HTTP. Master the three things—using URLs to locate resources, methods to express intent, and status codes to convey results—and understand the six stages of the request path, and you have the basic framework for reading, designing, and debugging interfaces. The rest comes down to discipline: consistent naming, distinguishable errors, and controlled changes.