العربية

What Is an API? A Beginner's Guide to REST, SOAP, GraphQL and gRPC

What Is an API? A Beginner's Guide to REST, SOAP, GraphQL and gRPC

Last updated: December 3, 2026

Every time you sign in with a Google account, pay through a checkout page or open a weather app, one program is asking another program for something. The set of rules for that conversation is an API. Most explanations either bury you in definitions or jump straight into code. This one builds the mental model first, then shows a working request and response, then compares the four styles you will meet at work.

The short answer

⚡ The short answer: an API (application programming interface) is a contract between two programs: "send me a request shaped like this, and I will send back a response shaped like that." You do not need to know how the other side works inside. For most web and mobile work, start with REST.

What an API is, with a restaurant

You do not walk into a restaurant kitchen and cook your own meal. You tell the waiter what you want, the waiter takes the order to the kitchen, and the food comes back the same way. The waiter is the API. The menu is its documentation: it lists what you can ask for and how. The kitchen can change its stove, its staff or its recipes, and as long as the menu and the plates stay the same, you never notice.

A real example: when a shop offers "pay with a card" through a payment provider, the shop does not touch your card details. It sends a request to the provider's API, the provider charges the card and replies with success or failure. The shop only ever sees the reply.

The request and response cycle

  1. A client, which could be an app, a browser or a script, sends a request to a specific address. The request says what it wants: read something, create something, change something, delete something.
  2. The API checks who is asking, if the endpoint needs that.
  3. The server does the work.
  4. The API sends back a response with a status code (success, error, not found) and usually some data.

Here is a real one. This code starts a tiny local server with one endpoint, GET /api/books/<id>, and calls it twice using only Python's standard library:

import json, threading, urllib.request, urllib.error
from http.server import BaseHTTPRequestHandler, HTTPServer

BOOKS = {7: {"id": 7, "title": "Clean Code", "author": "Robert C. Martin", "available": True}}

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        book = BOOKS.get(int(self.path.rsplit("/", 1)[1]))
        self.send_response(200 if book else 404)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(json.dumps(book or {"error": "not found"}).encode())

server = HTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
base = f"http://127.0.0.1:{server.server_port}"

def call(path):
    try:
        r = urllib.request.urlopen(base + path)
        print(r.status, r.reason, r.headers["Content-Type"], r.read().decode())
    except urllib.error.HTTPError as e:
        print(e.code, e.reason, e.headers["Content-Type"], e.read().decode())

call("/api/books/7")
call("/api/books/99")

Running it printed:

200 OK application/json {"id": 7, "title": "Clean Code", "author": "Robert C. Martin", "available": true}
404 Not Found application/json {"error": "not found"}

Two things to notice. The status code tells the client what happened before it reads any data: 200 means it worked, 404 means that book does not exist. And the response body is JSON, a text format both sides understand regardless of the language they are written in.

Why APIs matter

  • Reuse. You do not build a payments system, a map service or an SMS gateway from scratch. You call one.
  • A clear boundary. An API exposes what a partner needs without handing over your database.
  • Independent scaling. Modern systems are many small services that talk through APIs, so one busy service can grow without touching the others.
  • One backend, many clients. An iOS app, an Android app and a web dashboard can all call the same API.

Four kinds of API by who can use them

  • Public (open) APIs. Anyone can sign up, usually get an API key and start calling. Mapping, weather and payment services are typical examples.
  • Partner APIs. Shared with specific business partners under an agreement, often with extra security such as OAuth tokens or IP restrictions.
  • Internal (private) APIs. Used inside one organization between its own systems.
  • Composite APIs. Combine several calls into one request, so a client gets what it needs in one round trip instead of four.
⚠️ "Internal" does not mean "safe". An internal API with no authentication is one compromised laptop away from being an open door. Authenticate every API, including the ones that only your own services call.

REST, SOAP, GraphQL and gRPC compared

StyleData formatGood forMain trade-off
RESTUsually JSONWeb and mobile apps, public APIsCan return too much or too little data per call
SOAPXMLEnterprise, banking and legacy integrationsVerbose and heavier to implement
GraphQLJSONComplex data with several kinds of clientSteeper learning curve; HTTP caching is harder
gRPCProtocol Buffers (binary)Fast service-to-service callsNot directly callable from a browser without a proxy layer

REST

REST stands for Representational State Transfer. A REST API exposes resources at URLs such as /api/books/7 and uses standard HTTP methods on them: GET reads, POST creates, PUT replaces, PATCH changes part of a resource and DELETE removes it. A key idea is that requests are stateless: each one carries everything the server needs, so any server in a group can answer it. REST is the sensible default for most web and mobile projects, because every language and tool can speak HTTP.

The weak point is data shape. If an endpoint returns a whole user object but you only need the name, you fetched too much. If you need data from three resources, you make three calls.

SOAP

SOAP is an older, more formal protocol that defines its messages in XML. The W3C specification describes it as a framework for exchanging structured information that can run over a variety of underlying protocols. You will mostly meet it when integrating with banks, insurers, government systems and older enterprise software. If a system you must connect to speaks SOAP, you usually do not get to choose. Libraries in most languages can generate the boilerplate from its WSDL description file.

GraphQL

GraphQL lets the client describe exactly the fields it wants, and the server returns that shape. Where REST might need two calls for a book and its author, one GraphQL query can fetch both:

query {
  book(id: 7) {
    title
    author { name }
  }
}

That fits products with several kinds of client, such as a phone app and a web app, that need different slices of the same data. The costs are a schema to design and maintain and weaker out-of-the-box HTTP caching, because queries typically go to one endpoint as POST requests rather than to many cacheable URLs.

gRPC

gRPC is a remote procedure call framework. Instead of thinking in resources, you define services and methods in a .proto file, and tools generate client and server code in many languages. Messages are encoded with Protocol Buffers, a compact binary format. It supports streaming in either direction, which makes it popular for communication between internal services where speed matters.

service BookService {
  rpc GetBook (BookRequest) returns (BookResponse);
  rpc ListBooks (ListBooksRequest) returns (stream BookResponse);
}

How to choose

  1. A public or general-purpose API for web and mobile? REST.
  2. Several different clients that each need different fields from a connected data model? Consider GraphQL, perhaps on top of existing services.
  3. Many internal services where latency and payload size matter? Look at gRPC.
  4. Integrating with a bank, government or older enterprise system? Expect SOAP and learn enough to work with it.

Real systems often use more than one. A company might offer REST publicly, GraphQL to its own apps and gRPC between internal services. They solve different problems at different layers.

Five ideas every beginner should know

1. Authentication vs authorization

Authentication asks who you are, usually proved with an API key, a token or OAuth. Authorization asks what you are allowed to do once you are known. A key can get you through the door while your account level decides which rooms you can enter. OAuth 2.0 is the common standard for letting one app act on your behalf at another service without ever seeing your password.

2. HTTP status codes

CodeMeaningWhen you see it
200 OKSuccessA read returned data
201 CreatedResource createdA POST succeeded
400 Bad RequestInvalid inputThe request was malformed
401 UnauthorizedNot authenticatedMissing or invalid credentials
403 ForbiddenNot allowedYou are known, but lack permission
404 Not FoundNo such resourceThe id or path does not exist
429 Too Many RequestsRate limit hitYou called too often
500 Internal Server ErrorServer faultThe provider's side broke

3. Rate limiting

Providers cap how many calls you can make in a period, to protect the service. If you receive a 429, slow down and retry later, ideally waiting longer after each failure.

4. Versioning

APIs change. A version in the URL or a header, like /v2/books, lets existing clients keep working while new ones use the new shape.

5. Keep secrets out of your code

Never commit an API key to a public repository or put it in front-end code that any visitor can read. Keep keys in environment variables or a secrets manager, and rotate any key that leaks.

Where to go next

Frequently Asked Questions

❓ What does API stand for?

Application Programming Interface. It is a defined way for one piece of software to ask another for data or actions.

❓ What is the difference between an API and a web service?

A web service is an API that is reached over a network. In everyday use the two words overlap, but not every API is a web service: a library's functions are also an API.

❓ Is REST the same as HTTP?

No. HTTP is the protocol. REST is an architectural style that uses HTTP methods and URLs to expose resources.

❓ Which should I learn first, REST or GraphQL?

REST. It is the most widely used, and understanding HTTP methods and status codes helps with every other style.

❓ What is an API key?

A secret string that identifies the calling application, so the provider can authenticate it and apply usage limits. Treat it like a password.

Sources

Add Valley4Techs as a Preferred Source

Follow us on Google News for the latest updates

Add Now
Comments