Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"label": "API Design & REST",
"position": 8,
"link": {
"type": "generated-index",
"description": "Learn how to build the bridges that connect your server to the world. Master RESTful principles, HTTP methods, and status codes."
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
---
sidebar_position: 8
title: "API Testing Tools"
sidebar_label: "8. Testing Tools"
description: "Learn how to test and debug your API endpoints using Postman, Thunder Client, and cURL."
---

You’ve designed your endpoints, chosen your status codes, and secured them with JWT. Now, how do you actually "call" them? Since we don't have a frontend yet, we use **API Testing Tools**.

These tools act as a "Universal Client" that can send any HTTP request to any server.

## Top 3 Tools for Developers

<Tabs>
<TabItem value="thunder" label="⚡ Thunder Client (Recommended)" default>

### Why we love it:
It is a lightweight extension that lives inside **VS Code**. You don't need to switch between apps!

* **Best For:** Quick testing during coding.
* **Pros:** Fast, stays in your editor, supports "Collections" and "Environment Variables."
* **Installation:** Search for "Thunder Client" in the VS Code Extensions marketplace.

</TabItem>
<TabItem value="postman" label="🚀 Postman">

### Why we love it:
The industry leader. If you work at a big tech company, they probably use Postman to document and share APIs.

* **Best For:** Complex projects and team collaboration.
* **Pros:** Advanced automated testing, beautiful documentation, and cloud sync.

</TabItem>
<TabItem value="curl" label="💻 cURL">

### Why we love it:
A command-line tool that comes pre-installed on almost every OS (Linux, Mac, Windows).

* **Best For:** Quick checks and automation scripts.
* **Example:**
```bash
curl -X GET https://api.codeharborhub.com/v1/users
```

</TabItem>
</Tabs>

## Anatomy of an API Request

When using these tools, you will need to configure four main parts:

1. **Method:** Select GET, POST, PUT, or DELETE.
2. **URL (Endpoint):** Where is your server running? (e.g., `http://localhost:5000/api/users`).
3. **Headers:** This is where you put your **Content-Type** (usually `application/json`) and your **Authorization** tokens.
4. **Body:** For POST and PUT requests, this is where you paste your JSON data.

## Understanding the Response

Once you hit "Send," the tool will show you:

```mermaid
graph TD
A[Hit Send] --> B{Server Process}
B --> C[Status Code: e.g., 200 OK]
B --> D[Response Time: e.g., 150ms]
B --> E[Response Body: The JSON Data]

```

## Professional Workflow: Environment Variables

Don't hardcode your URLs! Imagine you have 50 requests. If you change your port from `5000` to `8000`, you don't want to edit 50 requests manually.

**Use Variables:**

* Create a variable called `{{base_url}}`.
* Set it to `http://localhost:5000`.
* Your requests will look like: `{{base_url}}/users`.

*Now, when you go to production, you just change the variable once!*

## Summary Checklist

* [x] I have installed **Thunder Client** or **Postman**.
* [x] I know how to set the HTTP Method and URL.
* [x] I can send a JSON body in a POST request.
* [x] I understand how to read the Status Code and Response Body.

:::success 🎉 Module Complete!
You have mastered the theory of **Relational Databases** and **API Design**. You are now officially ready to start writing real code!
:::
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
---
sidebar_position: 6
title: "API Authentication"
sidebar_label: "6. Authentication"
description: "Learn how to secure your APIs using modern authentication methods like API Keys and JWT."
---

In the previous lessons, we built APIs that anyone could call. But in the real world, you don't want strangers deleting your data! **Authentication (AuthN)** is how the server verifies that a request is coming from a valid user.

## 🧐 Authentication vs. Authorization

These two sound similar, but they are very different. At **CodeHarborHub**, we use the "Office Building" analogy:

* **Authentication (AuthN):** Showing your ID card at the gate to enter the building. (*Who are you?*)
* **Authorization (AuthZ):** Your ID card only lets you into the 4th floor, not the CEO's office. (*What are you allowed to do?*)

## Common Auth Methods

Modern APIs usually use one of these three methods to keep things secure:

<Tabs>
<TabItem value="apikey" label="🔑 API Keys" default>

### Simple & Fast
The server gives the client a long, secret string (the Key). The client sends this key in the header of every request.
* **Best For:** Public APIs (like Google Maps or Weather APIs).
* **Risk:** If someone steals your key, they can act as you.

</TabItem>
<TabItem value="jwt" label="🎟️ JWT (Tokens)">

### The Industry Standard
**JSON Web Tokens** are like a digital "Boarding Pass." Once you login, the server gives you a signed token. You show this token for every future request.
* **Best For:** Modern Web and Mobile apps.
* **Feature:** It's **Stateless** (the server doesn't need to check the database every time).

</TabItem>
<TabItem value="oauth" label="🤝 OAuth 2.0">

### Third-Party Login
This allows you to "Login with Google" or "Login with GitHub."
* **Best For:** User convenience and high security.
* **Benefit:** You don't have to manage passwords; Google does it for you!

</TabItem>
</Tabs>

## The Token-Based Workflow (JWT)

This is the most common flow you will build as a Backend Developer:

```mermaid
sequenceDiagram
participant C as Client (User)
participant S as Server (API)
participant DB as Database

C->>S: 1. Login (Username + Password)
S->>DB: 2. Verify Credentials
DB-->>S: 3. Correct!
S->>S: 4. Generate JWT Token
S-->>C: 5. Send Token back
Note over C,S: Subsequent Requests
C->>S: 6. GET /profile (Header: Bearer <Token>)
S->>S: 7. Verify Token Signature
S-->>C: 8. Here is your Private Data!

```

## Best Practices for API Security

1. **Always use HTTPS:** Never send passwords or tokens over `http`. They can be easily stolen.
2. **Use the Authorization Header:** Don't put tokens in the URL. Use the standard header:
`Authorization: Bearer <your_token_here>`
3. **Set Expiration:** Tokens should not last forever. If a token is stolen, it should expire in a few hours.
4. **Don't Store Secrets in Frontend:** Never hardcode your API keys in your React or HTML code. Use `.env` files.

## Summary Checklist

* [x] I understand that Authentication proves **identity**.
* [x] I know the difference between Authentication and Authorization.
* [x] I understand the JWT "Boarding Pass" workflow.
* [x] I know that sensitive data must always be sent over HTTPS.

:::danger Security Warning
Never, ever commit your API keys or Secrets to **GitHub**! If you do, hackers can find them in seconds. Always use a `.gitignore` file to hide your environment variables.
:::
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
---
sidebar_position: 3
title: "HTTP Methods & Status Codes"
sidebar_label: "3. Methods & Status"
description: "Learn the vocabulary of the web—how to tell the server what to do and how to understand its response."
---

When you send a request to a REST API, you are essentially sending a message. To make sure the server understands you, you must use specific **Methods**. Once the server processes your request, it replies with a **Status Code**.

## HTTP Methods (The "Verbs")

Every request starts with a method that defines the **intent** of the action.

<Tabs>
<TabItem value="get" label="📖 GET" default>

### Purpose: Retrieve Data
Used when you want to "fetch" information. It is **Read-Only**.
* **Analogy:** Browsing a menu at a cafe.
* **Example:** `GET /users` (Get all users).

</TabItem>
<TabItem value="post" label="➕ POST">

### Purpose: Create Data
Used to send new data to the server to create a resource.
* **Analogy:** Placing a new order at the counter.
* **Example:** `POST /users` (Create a new account).

</TabItem>
<TabItem value="put" label="📝 PUT / PATCH">

### Purpose: Update Data
* **PUT:** Replaces the entire resource.
* **PATCH:** Updates only specific parts (like just the email).
* **Analogy:** Changing your mobile number on an existing account.

</TabItem>
<TabItem value="delete" label="🗑️ DELETE">

### Purpose: Remove Data
Used to delete a specific resource.
* **Analogy:** Canceling your subscription.
* **Example:** `DELETE /users/1` (Delete user with ID 1).

</TabItem>
</Tabs>

## HTTP Status Codes (The Feedback)

After you send a request, the server sends back a 3-digit number. This tells the client exactly what happened.

| Range | Category | "Desi" Meaning | Typical Examples |
| :--- | :--- | :--- | :--- |
| **2xx** | **Success** | "Sab sahi hai!" (All Good) | **200 OK**, **201 Created** |
| **3xx** | **Redirection** | "Rasta badal lo." (Go elsewhere) | **301 Moved Permanently** |
| **4xx** | **Client Error** | "Tumhari galti hai." (Your fault) | **400 Bad Request**, **404 Not Found** |
| **5xx** | **Server Error** | "Meri galti hai." (My fault) | **500 Internal Server Error** |

## Understanding the "Big Three" Codes

1. **200 OK:** The request was successful, and here is your data!
2. **404 Not Found:** The URL you requested doesn't exist. (The "classic" internet error).
3. **500 Internal Server Error:** Your code crashed on the server. The client did nothing wrong, but the backend failed.

## Summary Checklist
* [x] I know that **GET** is for reading and **POST** is for creating.
* [x] I understand the difference between **PUT** (Full update) and **PATCH** (Partial).
* [x] I can identify that **4xx** codes mean the issue is on the user's side.
* [x] I know that **201** is the standard code for a successful "Create" action.

:::warning Common Beginner Mistake
Never use **GET** to send sensitive data like passwords! Data in a GET request is visible in the URL. Always use **POST** with a "Body" for secure information.
:::
105 changes: 105 additions & 0 deletions absolute-beginners/backend-beginner/api-design/json-apis.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
---
sidebar_position: 5
title: "JSON & API Communication"
sidebar_label: "5. JSON APIs"
description: "Learn about JSON, the universal data format for modern API communication."
---

When a Waiter (the API) brings your order from the Kitchen (the Server), the food is served on a **Plate**. In the digital world, **JSON** is that plate.

**JSON** stands for **JavaScript Object Notation**. It is a lightweight, text-based format that is easy for humans to read and even easier for machines to parse.

## 🧐 Why JSON?

Before JSON, the world used **XML**, which was very bulky and hard to read. JSON won the "format war" because:
1. **Lightweight:** It uses very few characters, making it fast to send over the internet.
2. **Language Independent:** Even though it has "JavaScript" in the name, almost every language (Python, Java, PHP, C#) can read it.
3. **Key-Value Pairs:** It organizes data exactly like a dictionary or a map.

## The Structure of a JSON Object

A JSON object is wrapped in curly braces `{}` and contains data in `key: value` pairs.

```json
{
"id": 101,
"name": "Ajay Dhangar",
"isMentor": true,
"skills": ["React", "Node.js", "SQL"],
"address": {
"city": "Mandsaur",
"state": "MP"
}
}
```

### Supported Data Types

<Tabs>
<TabItem value="strings" label="🔤 Strings" default>
Text wrapped in double quotes: `"Hello CodeHarborHub"`
</TabItem>
<TabItem value="numbers" label="🔢 Numbers">
Integers or decimals: `25` or `99.99`
</TabItem>
<TabItem value="arrays" label="📚 Arrays">
Ordered lists inside brackets: `["JavaScript", "HTML"]`
</TabItem>
<TabItem value="objects" label="📂 Objects">
Nested data inside braces: `{"key": "value"}`
</TabItem>
</Tabs>

## Sending and Receiving JSON

When you build a backend at **CodeHarborHub**, you will deal with JSON in two ways:

### 1. The Request Body

When a user registers, they send their data to your server as a JSON string.

```http
POST /users
Content-Type: application/json

{
"username": "coder_ajay",
"password": "securepassword123"
}
```

### 2. The Response

Your server processes the logic and sends back a JSON response.

```json
{
"status": "success",
"message": "User created successfully",
"userId": 502
}
```

## Tools for JSON

### 1. JSON Formatter

Raw JSON can sometimes look like a giant "wall of text." Use a browser extension like **JSON Viewer** to make it look beautiful and organized.

### 2. JSON.stringify() vs JSON.parse()

If you are using JavaScript:

* **`JSON.stringify(obj)`**: Converts a JS object into a JSON string (to send to a server).
* **`JSON.parse(str)`**: Converts a JSON string into a JS object (to use in your code).

## Summary Checklist

* [x] I understand that JSON is a text format for storing and transporting data.
* [x] I know that JSON uses Key-Value pairs.
* [x] I can identify different data types like Strings, Numbers, and Arrays in JSON.
* [x] I understand that `Content-Type: application/json` is required in the header.

:::tip Pro-Tip
Always validate your JSON! A single missing comma `,` or a missing double quote `"` will cause your entire API request to fail. Use a tool like **JSONLint** to check your work.
:::
Loading
Loading