Knowledge / Computer Applications / API design: GraphQL, gRPC and OpenAPI

API design: GraphQL, gRPC and OpenAPI

Computer Applications (MCA) · Enterprise and web development · free study notes for exams, placements and interviews

In short

API design is the discipline of defining the contract between a client and a service: what can be asked, in what shape, with what errors and guarantees. Three contract styles dominate today - OpenAPI (a machine-readable description of an HTTP/JSON API), GraphQL (a typed query language where the client selects exactly the fields it needs) and gRPC (a binary, contract-first remote procedure call framework over HTTP/2). MCA and B.Tech syllabi examine them under "web services and service-oriented architecture", and placement rounds at Flipkart, Swiggy, Zomato, Razorpay, Zerodha, PhonePe, Jio, Infosys, TCS, Wipro, Freshworks and Zoho routinely ask which style suits a given problem and why. In Indian public digital infrastructure the same three appear: ONDC and Account Aggregator publish OpenAPI/JSON contracts, while internal microservice fabrics in large product companies are mostly gRPC.

Explained

Why a contract-first API at all

OpenAPI (formerly Swagger)

GraphQL

gRPC and Protocol Buffers

Choosing between them, and combining them

Versioning, governance and Indian practice

Key points

Formulas and examples

Over-fetch ratio = bytes received / bytes actually used (dimensionless; 1.0 is ideal)
Payload efficiency η = useful bytes / total bytes = 1 / over-fetch ratio
Query count for N parents, naive: Q = 1 + N; with batching: Q = 2
Total latency T = R × RTT + Σ(server processing time), R = number of sequential round trips (ms)
GraphQL complexity cost C = Σ over fields of (field cost × product of enclosing list sizes)
Bandwidth B = payload size × requests per second × duration (bytes); 1 GB = 10⁹ bytes here
Compression saving = 1 − (new size / old size)

Example 1 - over-fetching on a mobile list screen. A REST endpoint returns a full user object of 2,400 bytes; the screen uses only id, name, avatarUrl - 180 bytes.

Example 2 - the N+1 problem costed. 50 authors are listed, each with their book count. One DB round trip = 8 ms.

Example 3 - GraphQL query cost check. Rule: each object node costs 1; cost is multiplied by list sizes. Query asks posts(first: 50) { comments(first: 20) { author { name } } }.

Example 4 - gRPC/Protobuf versus JSON bandwidth and egress cost. The same telemetry message is 142 bytes as JSON and 38 bytes as protobuf, at 1,000 requests per second.

Example 5 - round trips on a 4G connection. RTT = 120 ms; server processing = 20 ms per call. A profile screen needs user, then orders, then product details (each depends on the previous).

OpenAPI / HTTP+JSONGraphQLgRPC
Contract artefactOpenAPI YAML/JSONSDL schema.proto file
Wire formatText JSONText JSONBinary protobuf
TransportHTTP/1.1 or HTTP/2HTTP (usually POST), WS for subscriptionsHTTP/2 only
EndpointsMany URLsOne endpointOne per service method
Client picks fieldsNoYesNo
StreamingSSE / WebSocket separatelySubscriptionsNative, four modes
Browser supportNativeNativeNeeds gRPC-Web proxy
HTTP cachingEasy (GET + ETag)Hard (POST)Not applicable
Codegen maturityGoodGood (typed clients)Excellent
Error modelHTTP status codes200 + errors arraygRPC status codes
Human-readable on wireYesYesNo
Typical usePublic/partner APIsBFF for apps and webInternal microservices
syntax = "proto3";
package catalog.v1;

service Catalog {
  rpc GetProduct (GetProductRequest) returns (Product);          // unary
  rpc WatchPrice (GetProductRequest) returns (stream PriceTick);  // server streaming
}
message GetProductRequest { string sku = 1; }
message Product {
  string sku   = 1;
  string name  = 2;
  int64  paise = 3;      // price in paise - integer money, never float
  reserved 4;            // 'mrp' removed in v1.3; tag never reused
}
type Query { product(sku: ID!): Product }
type Product { sku: ID!  name: String!  pricePaise: Int!  reviews(first: Int = 10): ReviewConnection! }
# client asks for only what it needs
query P($sku: ID!) { product(sku: $sku) { name pricePaise } }

Where it is used

Interview questions

Common mistakes

Related topics

REST APIs · Authentication and authorisation: sessions, OAuth and JWT · Spring Boot and microservices development · Back-end development with Node.js · TypeScript and Angular · Web services, SOAP and message queues

Open in the Knowledge reader →Find jobs →