# Understanding APIs — The Convention You Were Already Using Without Knowing

So if you’ve landed on this blog, then probably one of these reasons brought you here.

*   Maybe you want to understand **what an API (Application Programming Interface) actually is**.
    
*   Or maybe you’re curious about the **foundational magic behind apps** — like *where does all this data actually come from?*
    

There could be many other reasons too.

But if we combine all of them into one simple thing, then maybe it just means this:

> **You’re a curious person — someone who likes to stay self-prepared and figure things out on their own.**

* * *

## Before We Dive Into APIs

Before we go into the details of APIs, let’s first look at their **real-world applications**.

Like:

*   Are they actually being used somewhere?
    
*   Or are we just torturing ourselves again by studying this only to follow the syllabus? 😅
    

* * *

## Real-World Examples You Might Have Seen

Recently, you must have seen things like:

> “I built an **AI SaaS** — now you can track all your different orders in one single platform just by connecting your accounts.”

Or maybe something like:

> “You can even **build your own crypto exchange** by interacting with validators.”

* * *

## Let’s Think of a Simple Scenario

Imagine this.

You’re using an app, and the company is showing you a **dashboard or presentation**.

All the data is stored on **their server**.

Now obviously, in that presentation, you want the **latest real-time data**, right?

So whenever you click a button, your app basically tells the server:

> “Hey, the user is requesting this data — send it to me.”

The server then:

1.  **Authenticates the request**
    
2.  **Processes it**
    
3.  **Sends the required data back**
    

* * *

## So… What Exactly Is an API?

If I explain an **API in one simple word**, think of it as a **mediator**.

It takes the message:

*   **From here → to there**
    
*   **From there → back to here**
    

In technical terms, it acts as a bridge between the **client and the server**.

* * *

## But Is That All?

Now the question is:

> Is an API just a way for a client and server to send requests and responses?

The answer is:

**Yes… that’s it.**

But don’t underestimate that *“just.”*

This is the **powerful mechanism** that helps everything run smoothly:

*   from a **simple todo app**
    
*   to **massive e-commerce platforms**
    

* * *

## The Interesting Part

Now here’s something interesting.

If every app can talk to its server, just like we humans talk to each other, then have you noticed something?

When **humans communicate**, we have:

*   different languages
    
*   different vocabulary
    
*   different grammar
    

That’s why we chose a **common global language** so we can communicate efficiently, no matter which corner of the world we’re in.

* * *

## Apps Have Languages Too

In the same way, **apps also follow different protocols**.

You can think of these protocols as:

*   rules
    
*   structure
    
*   grammar
    

But in this blog, we’ll focus on one of the **most famous and commonly used API styles**:

> **REST (Representational State Transfer)**

And trust me —

**you’ve already been using it without even realizing.**

![](https://cdn.hashnode.com/uploads/covers/65e69c810f550f9e1cafb2e5/a04d7a6e-0eb5-46c2-9343-aeb8f2ef7146.png align="center")

## What is REST?

**REST (Representational State Transfer)** is an **architectural style**.

That means it is a **set of rules or conventions** that define **how communication should happen between the client and the server**.

* * *

## Think of REST Like an Agreement

You can think of REST as a kind of **agreement between two parties**.

For example, imagine two people deciding:

> “We’ll talk in **English**, and whenever I ask for something, I’ll ask for it in a **specific format**.”

Both people understand the rules of communication, so the conversation becomes **clear and efficient**.

* * *

## That’s Exactly What REST Does

REST works in a very similar way.

It defines **how clients should request data** and **how servers should respond** so that communication stays **structured, predictable, and easy to understand**.

In simple words:

> **REST is basically an agreement on how communication should happen between the client and the server.**

* * *

## 🍽️ Analogy — The Restaurant One (Classic but Gold)

Imagine you’re in a restaurant.

Let’s map the roles:

*   **You → Client** *(browser or mobile app)*
    
*   **Kitchen → Server** *(where the data and logic live)*
    
*   **Waiter → REST API**
    

* * *

### How the Interaction Happens

You don’t walk straight into the kitchen.

Instead, you give your order to the waiter in a specific format:

> “I’d like one **paneer butter masala**.”

The process then looks like this:

1.  The **waiter takes your order**
    
2.  The waiter **communicates it to the kitchen**
    
3.  The **kitchen prepares the dish**
    
4.  The waiter **brings the dish back to you**
    

* * *

### The Waiter Also Follows Some Rules

Just like in a real restaurant, the waiter operates under certain rules:

*   **Orders must be taken in a specific way**
    
*   **Some items are available from the kitchen, some aren’t**
    
*   **The response comes back in a defined format**
    

* * *

### So What Does This Mean for REST?

That’s basically what a **REST API** does.

It acts as the **middle layer** that:

*   receives requests from the **client**
    
*   communicates with the **server**
    
*   and returns the **response in a structured way**
    

* * *

## 🔑 The 4 Main REST Actions (HTTP Methods)

In REST APIs, communication between the **client and the server** happens through **HTTP methods**.

These methods define **what kind of action the client wants to perform on the server’s data**.

Here are the **four most commonly used HTTP methods**:

| HTTP Method | Meaning | Real Example |
| --- | --- | --- |
| **GET** | Request data from the server | Fetch a user’s profile |
| **POST** | Send new data to the server | Create a new account |
| **PUT / PATCH** | Update existing data | Change a password |
| **DELETE** | Remove data | Delete an account |

* * *

### Quick Way to Remember

Think of it like **basic operations you perform on data**:

*   **GET → Read data**
    
*   **POST → Create data**
    
*   **PUT/PATCH → Update data**
    
*   **DELETE → Remove data**
    

These four actions are often called **CRUD operations**:

*   **C → Create**
    
*   **R → Read**
    
*   **U → Update**
    
*   **D → Delete**
    

And almost every modern web application uses these operations when interacting with APIs.

* * *

## 🌐 URL Structure — “Routes” in Express

Here I’ll take a few **route examples** that we developers often write.

These examples follow **REST conventions**.

```javascript
// All of these follow REST conventions

app.get('/users', getAllUsers)        // get all users
app.get('/users/:id', getUserById)    // get a specific user
app.post('/users', createUser)        // create a new user
app.put('/users/:id', updateUser)     // update a user
app.delete('/users/:id', deleteUser)  // delete a user
```

* * *

## Notice the Simple Pattern

If you observe carefully, there is a **very clear pattern** behind REST APIs.

*   **Noun → Resource**  
      
    Examples: `/users`, `/posts`, `/orders`
    
*   **Verb → HTTP Method**  
      
    Examples: `GET`, `POST`, `PUT`, `DELETE`
    

The **URL represents the resource**, while the **HTTP method represents the action**.

* * *

## A Small REST Rule

REST encourages developers to **avoid putting verbs in the URL**.

❌ **Not REST-friendly**

```plaintext
/getUser
```

✅ **REST-compliant**

```plaintext
GET /user
```

The idea is simple:

> **Let the HTTP method describe the action, and let the URL represent the resource.**

* * *

## 📦 Request and Response Format

So by now we’ve understood **how to make requests in a clean way**, but we still haven’t talked about something important.

> What does the data we send with the request or receive in the response actually look like?

Is there a **specific format** for it, or is there **no format at all**?

* * *

## The Most Common Format — JSON

In REST APIs, data usually travels in **JSON format**.

Here’s an example of a response from this endpoint:

`GET /users/1`

```json
{
  "id": 1,
  "name": "Arjun",
  "email": "arjun@example.com"
}
```

This response simply returns the **data of a specific user**.

* * *

## How This Looks in Express

If you’ve worked with **Express**, you’ve probably written something like this many times:

```javascript
res.json({ id: 1, name: "Arjun" }) // this is a REST response
```

Here, the server is **sending data back to the client in JSON format**, which is the **standard way REST APIs usually communicate**.

* * *

## 🔁 Stateless — An Important Rule

One of REST’s **golden rules** is that **every request should be complete on its own**.

This means the **server doesn’t remember what you asked for earlier**.  
Every time you make a request, you need to send the **full context along with it**.

For example:

*   a **token**
    
*   a **user ID**
    
*   or other required authentication details
    

* * *

## Analogy

Imagine visiting a doctor who **has no record of your medical history**.

Every time you visit, you have to **explain everything again from the beginning**.

A REST server works in a **very similar way** — it’s intentionally a bit **“amnesiac.”**

And surprisingly, that’s actually a **good thing**.

Because it helps keep the server:

*   **more scalable**
    
*   **simpler to manage**
    
*   **easier to distribute across systems**
    

That's why when you log in, your app stores a token — and sends it with every request so the server knows who you are.

*So the next time you write* `app.get()` *in Express — you're not just writing a route. You're following a globally accepted convention used by millions of apps worldwide. That's REST.*

* * *

## 🤔 “But Wait — Do You Have to Follow REST?”

No. **Not at all.**

Even if you ignore REST conventions and write an API like this:

```javascript
app.get('/users', (req, res) => {
  // Sent a body in GET — Express will still allow it
  const data = req.body // technically this will work
  res.json({ msg: "yep, it worked" })
})

app.patch('/users/:id', (req, res) => {
  // Only fetched the user in PATCH — this will also work
  const user = await User.findById(req.params.id)
  res.json(user)
})

app.delete('/users/:id', (req, res) => {
  // Created a new user in DELETE — this will still work
  const newUser = await User.create({ name: "Arjun" })
  res.json(newUser)
})
```

…it will **still work**.

The server will send data.  
  
The client will receive it.  
  
And no error will magically appear.

* * *

## Where Problems Start ?🤔

The real problem appears when **you’re not working alone**.

Imagine a new developer joins your team.

They see this:

```javascript
DELETE /users/1
```

Naturally they assume:

> “This will delete the user.”

But in reality, your code is **creating a new user there**.

Now:

*   they’re confused
    
*   you’re confused
    
*   and the client is confused 🤯
    

* * *

## Another Real-World Problem

Imagine a **frontend developer** using your API.

They send a **body with a GET request**.

But many **HTTP clients and browsers silently strip the body from GET requests**.

So what happens?

*   The data disappears
    
*   No error shows up
    
*   And you spend **three hours hunting a bug**
    

* * *

## So What Exactly Is REST Then?

REST isn’t a **strict rule**.

It’s more like an **agreement**.

And agreements are only followed when they actually make things **easier for everyone involved**.

So the real question becomes:

> **Why did REST become the hero?**

* * *

## Before REST — There Was SOAP

Before REST became popular, developers mostly used **SOAP (Simple Object Access Protocol)**.

The word **“Simple”** was in the name — but the experience was anything but simple.

To make a single request, you often had to:

*   Manually write an **XML document**
    
*   Wrap an **RPC call** inside it
    
*   Send the whole thing inside a **SOAP envelope**
    
*   Deliver it to a specific endpoint using **POST**
    

* * *

## Documentation Was… Huge

When companies like **ReadMe** and **Salesforce** launched their early APIs, the documentation sometimes came as:

> **400+ page PDF manuals** 😅

Not exactly beginner-friendly.

* * *

## Enter REST (Year 2000)

In **2000**, **Roy Fielding** — one of the co-authors of the **HTTP/1.1 specification** — introduced **REST** in his **PhD dissertation**.

His idea was refreshingly simple:

> **Keep the same URL, just change the HTTP method.**

Example:

```javascript
GET /posts   → fetch posts
POST /posts  → create a new post
```

Same URL.  
  
Different intent.  
  
**Clean and readable.**

* * *

## Why Developers Loved It

Developers who were tired of SOAP’s complexity quickly started shifting to **REST during the mid-2000s**.

And today, REST has become **one of the most widely used API architectures on the web**.

* * *

## The Real Reason REST Conventions Exist

REST conventions aren’t followed just to make the **API work**.

They’re followed so that:

*   other developers
    
*   your teammates
    
*   and even **your future self**
    

don’t go crazy trying to understand the system.

> **Good conventions make collaboration possible.**

And REST is one of those conventions. 😄

* * *

## 📡 Status Codes

![](https://cdn.hashnode.com/uploads/covers/65e69c810f550f9e1cafb2e5/8586e3ea-fd31-4737-b853-537d7db72321.png align="center")

Think of it like this:

When a **waiter takes your order to the kitchen and comes back**, they don’t just bring the dish.  
There’s also an **implicit message** with it.

For example:

*   “Here you go, this is your order.” ✅
    
*   “Sorry, that dish isn’t on the menu.” ❌
    
*   “The kitchen caught fire today, nothing’s coming out.” 💀
    

HTTP responses work **the same way**.

Along with the data, you also get a **3-digit status code** that tells you **what happened with the request**.

* * *

## 📊 Categories — There Are 5 Families

| Range | Meaning | Vibe |
| --- | --- | --- |
| **1xx** | Informational | “Yeah, I’m listening.” |
| **2xx** | Success | “Done, here you go.” |
| **3xx** | Redirection | “Not here, go there.” |
| **4xx** | Client Error | “You messed up.” |
| **5xx** | Server Error | “My fault.” |

In practice, developers **rarely deal directly with 1xx and 3xx**, so most of the time you’ll focus on:

*   **2xx → Success**
    
*   **4xx → Client errors**
    
*   **5xx → Server errors**
    

* * *

## 🧑‍💻 Status Codes You’ll Use Daily (with Express)

### ✅ 2xx — Everything Worked

```javascript
res.status(200).json({ users }) // data fetched successfully
res.status(201).json({ user })  // new resource created (after POST)
res.status(204).send()          // action done, nothing to return (after DELETE)
```

* * *

### ❌ 4xx — Client Made a Mistake

```javascript
res.status(400).json({ error: "Invalid input" })      // wrong data sent
res.status(401).json({ error: "Login first" })        // not authenticated
res.status(403).json({ error: "No permission" })      // logged in but not allowed
res.status(404).json({ error: "Not found" })          // resource doesn’t exist
```

* * *

### 💥 5xx — Server Made a Mistake

```javascript
res.status(500).json({ error: "Something went wrong" }) // server crash or bug
```

* * *

### 🧠 Quick Intuition

You can remember them like this:

*   **2xx → Everything is good**
    
*   **4xx → Client mistake**
    
*   **5xx → Server mistake**
    

Status codes help both **developers and applications understand what happened** without even looking deeply into the response body.

* * *

## 🤯 401 vs 403 — This Confuses Almost Everyone

This is a **very common point of confusion** when working with APIs.

| Status Code | Meaning | Simple Explanation |
| --- | --- | --- |
| **401 Unauthorized** | Authentication required | “First tell me who you are.” |
| **403 Forbidden** | Access denied | “I know who you are, but you’re not allowed in.” |

### Quick Interpretation

*   **401 → Token is missing or invalid**
    
*   **403 → You are authenticated, but you don’t have the required role or permission**
    

* * *

### Real Example

```javascript
// 401 — no token sent
if (!req.headers.authorization) {
  return res.status(401).json({ error: "Token not found" })
}

// 403 — token is valid but user isn't an admin
if (user.role !== 'admin') {
  return res.status(403).json({ error: "Admin access required" })
}
```

* * *

## ⚖️ 200 vs 201 — Another Thing People Often Ignore

Another small detail that beginners often miss is the difference between **200** and **201**.

```javascript
app.get('/users', (req, res) => {
  res.status(200).json({ users }) // data fetched → 200
})

app.post('/users', (req, res) => {
  // new user created → use 201 Created, not 200
  res.status(201).json({ user })
})
```

Most beginners return **200 for POST requests** as well.

Technically it will still work.  
  
But according to **REST conventions**, if a **new resource was created**, the correct status code is:

> **201 — Created**

* * *

## 🫖 The Legendary Status Code

There’s actually a **legendary HTTP status code**:

> **418 — “I’m a Teapot”**

This started as an **April Fool’s joke** added to an RFC in **1998**.

The idea was simple and hilarious:

If you send a request asking a **teapot to brew coffee**, the server should respond with:

```javascript
418 I'm a teapot
```

The joke came from an experimental protocol called:

**HTCPCP — Hyper Text Coffee Pot Control Protocol**

Example request:

```javascript
BREW /coffee HTTP/1.1
```

And the server replies:

```javascript
418 I'm a teapot
```

Even though it started as a joke, the **status code still officially exists in the HTTP specification**.

Many developers love using it as a **fun Easter egg in APIs or error pages**. 😄

* * *

## 🧾 Conclusion

If I had to summarize this entire blog in **one paragraph**, it would be this:

> **APIs act as a mediator between the client and the server.**  
> **REST is an agreement that defines how this communication should happen.**  
> **HTTP methods tell us what action we want to perform, and status codes tell us what actually happened.**
> 
> Together, all of this powers a system that runs inside **almost every app in the world — right now, as you’re reading this.**

* * *

### One Thing to Remember

Whenever you write something like:

*   `app.get()`
    
*   `res.status(201)`
    
*   or create a clean route like `/users/:id`
    

you’re not just using **Express** (or any similar framework).

You’re following a **globally accepted convention used by millions of developers around the world**.

> These aren’t small details.  
> **They’re the foundations on which real-world applications are built.**

* * *

### Before You Go 😄

If you found this blog helpful, share it with **that one friend who’s still writing routes like:**

```javascript
/getUserDataPlease
```

* * *

### Until Next Time

Till then, we’re off to **brew a new topic** — and you keep sipping your coffee. ☕

We’ll meet again on another day, probably while enjoying **another cup of coffee.**
