API Fundamentals Course
API Fundamentals
/
Intermediate

API Contracts

Definition

A formal, documented agreement between the API provider (backend) and the API consumer (frontend) regarding exactly what data will be sent and what data will be returned.

Explain Like I'm New

A promise. The backend promises: 'If you send me an ID as a number, I guarantee I will return an object with a `firstName` string.' If the backend suddenly changes `firstName` to `givenName` without telling the frontend, they broke the contract, and the frontend app crashes.

Real World Example

The Frontend and Backend teams meet on Monday. They agree on an API Contract for the new `/checkout` endpoint. They write it down in Swagger. Now, both teams can work completely independently for the rest of the week, knowing exactly how the systems will eventually connect.

Common Use Cases

  • •Team coordination
  • •Microservices alignment
  • •Consumer-Driven Contract Testing

Interactive Example

/*
  A Basic API Contract Agreement
  
  ENDPOINT: POST /api/v1/orders
  
  FRONTEND PROMISES TO SEND:
  {
    "itemId": number (Required),
    "qty": number (Default: 1)
  }
  
  BACKEND PROMISES TO RETURN (201 Created):
  {
    "orderId": string,
    "status": "PENDING" | "SHIPPED"
  }
  
  **If either side deviates from this exact shape, the system fails.**
*/

Interview Questions

basic

  • What happens if a backend developer 'breaks the API contract'?

intermediate

  • How do tools like OpenAPI enforce API contracts?

Flash Cards

Question

Break contract?

Click to reveal answer
Answer

The client applications relying on that API (Mobile apps, React apps, Partner companies) will instantly crash because they receive data in a format they aren't programmed to handle.

Question

How tools enforce?

Click to reveal answer
Answer

You can set up automated tests that intercept backend responses and compare them to the OpenAPI blueprint. If the backend returns `givenName` but the blueprint says `firstName`, the test fails and stops the deployment.