Learn what APIs are, why they matter, and how they work - from absolute basics to advanced concepts. Your complete resource before searching Google!
What is an API and why do you need it - starting from the basics
API (Application Programming Interface) explained - what it is and why it's so important. Illustrated with real-life examples.
API (Application Programming Interface) is a bridge or medium that allows two software applications to communicate with each other.
Imagine you're at a restaurant:
You can't go directly into the kitchen. You must order through the waiter and receive your food through them. API works exactly like that waiter!
When you open a Weather app:
// API Request Example
GET https://api.weather.com/current?city=London
// API Response Example
{
"city": "London",
"temperature": "18°C",
"condition": "Cloudy"
}
| Reason | Explanation |
|---|---|
| Data Access | Access others' data (weather, maps, payment) |
| Security | No direct database access, controlled access via API |
| Reusability | Build once, use in many apps |
| Scalability | Frontend and Backend stay separate, easy to scale |
https://httpbin.org/getREST (Representational State Transfer) explained - why most modern APIs follow this architecture.
REST (Representational State Transfer) is an architectural style - a set of rules or patterns for building APIs.
| Principle | Meaning |
|---|---|
| Stateless | Each request is independent, server doesn't remember previous requests |
| Client-Server | Frontend and Backend are separated |
| Uniform Interface | Uses standard HTTP methods (GET, POST, PUT, DELETE) |
| Cacheable | Responses can be cached for better performance |
https://api.example.com/v1/users // All users
https://api.example.com/v1/users/123 // User with ID 123
https://api.example.com/v1/users/123/posts // Posts by user 123
| Method | Purpose | Example |
|---|---|---|
| GET | Retrieve data (Read) | GET /users - get all users |
| POST | Create new data (Create) | POST /users - create new user |
| PUT | Update entire data (Update) | PUT /users/1 - update user 1 |
| DELETE | Remove data (Delete) | DELETE /users/1 - delete user 1 |
https://jsonplaceholder.typicode.com/usershttps://jsonplaceholder.typicode.com/posts{"title": "Test", "body": "Hello"}What's the difference between API and REST API? Many get confused - this clears it up.
API is a general concept - any software interface.
REST API is a specific type of API - one that follows REST rules.
In other words, all REST APIs are APIs, but not all APIs are REST APIs!
| Type | What It Is | Use Case |
|---|---|---|
| REST API | HTTP-based, JSON response | Most web/mobile apps |
| SOAP API | XML-based, strict rules | Banking, Enterprise |
| GraphQL API | Query language, flexible | Facebook, GitHub |
| WebSocket API | Real-time, bidirectional | Chat, Gaming |
| RPC API | Remote procedure calls | Internal services |
// REST API - Simple JSON
GET /api/users/1
Response: {"id": 1, "name": "John"}
// SOAP API - Complex XML
1
What gets sent in an API call (Request) and what comes back (Response) - detailed breakdown.
| Part | What It Contains | Example |
|---|---|---|
| URL/Endpoint | Where the request goes | https://api.example.com/users |
| Method | What action to perform | GET, POST, PUT, DELETE |
| Headers | Extra information | Authorization, Content-Type |
| Body | Data being sent (POST/PUT) | {"name": "John"} |
| Query Params | Filter/options | ?page=1&limit=10 |
POST https://api.example.com/users?role=admin HTTP/1.1
Host: api.example.com
Content-Type: application/json
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
{
"name": "John Doe",
"email": "john@example.com",
"age": 25
}
| Part | What It Contains | Example |
|---|---|---|
| Status Code | Indicates success/error | 200, 201, 400, 404, 500 |
| Headers | Response metadata | Content-Type, Cache-Control |
| Body | Actual data | JSON/XML data |
HTTP/1.1 201 Created
Content-Type: application/json
X-Request-Id: abc123
{
"success": true,
"data": {
"id": 456,
"name": "John Doe",
"email": "john@example.com"
},
"message": "User created successfully"
}
https://httpbin.org/post (POST method)Important API concepts - JSON, Status Codes, Headers
JSON (JavaScript Object Notation) - the standard format for sending and receiving data in APIs.
JSON (JavaScript Object Notation) is a data format that is both human-readable and machine-parseable. Almost all APIs use JSON.
{
"string": "Hello World",
"number": 123,
"decimal": 45.67,
"boolean": true,
"null": null,
"array": [1, 2, 3],
"object": {
"nested": "value"
}
}
"name""Hello"// User Object
{
"id": 1,
"name": "John Doe",
"email": "john@example.com",
"isActive": true,
"roles": ["admin", "user"],
"profile": {
"avatar": "https://...",
"bio": "Developer"
}
}
// API Response with Array
{
"success": true,
"count": 3,
"data": [
{"id": 1, "name": "John"},
{"id": 2, "name": "Jane"},
{"id": 3, "name": "Bob"}
]
}
| JSON | XML |
|---|---|
| Lightweight | Verbose |
| Easy to read | More complex |
| Native to JavaScript | Needs parsing |
| Modern APIs | Legacy/Enterprise |
https://jsonplaceholder.typicode.com/users/1200 OK, 404 Not Found, 500 Error - what do status codes in API responses mean.
| Range | Category | Meaning |
|---|---|---|
| 1xx | Informational | Processing in progress |
| 2xx | Success | Everything is OK |
| 3xx | Redirection | Need to go elsewhere |
| 4xx | Client Error | Your mistake |
| 5xx | Server Error | Server's problem |
| Code | Name | When It Occurs |
|---|---|---|
| 200 | OK | Request successful (GET/PUT) |
| 201 | Created | New resource created (POST) |
| 204 | No Content | Success but no body (DELETE) |
| 400 | Bad Request | Invalid data sent |
| 401 | Unauthorized | Not logged in |
| 403 | Forbidden | No permission |
| 404 | Not Found | Resource doesn't exist |
| 422 | Unprocessable | Validation error |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Error | Server crashed |
| 502 | Bad Gateway | Proxy/Gateway error |
| 503 | Service Unavailable | Server down/maintenance |
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Email is required",
"field": "email"
}
}
https://httpbin.org/status/200 - Successhttps://httpbin.org/status/404 - Not Foundhttps://httpbin.org/status/500 - Server ErrorWhat is an API Endpoint, how URL structure works, what are Query Parameters.
An endpoint is a specific URL where an API request is sent. Each endpoint performs a specific function.
https://api.example.com/v1/users?page=1&limit=10
|_____| |_____________| |_| |___| |______________|
| | | | |
Protocol Host Version Path Query Params
| Method | Endpoint | Action |
|---|---|---|
| GET | /users | Get all users |
| GET | /users/123 | Get user by ID |
| POST | /users | Create new user |
| PUT | /users/123 | Update user |
| DELETE | /users/123 | Delete user |
| GET | /users/123/posts | Get user's posts |
Extra options sent after ? in the URL:
// Pagination
GET /users?page=2&limit=20
// Filtering
GET /products?category=electronics&price_max=1000
// Sorting
GET /posts?sort=created_at&order=desc
// Searching
GET /users?search=john&fields=name,email
| Type | Use Case | Example |
|---|---|---|
| Path Param | Specific resource | /users/123 |
| Query Param | Filter, sort, page | /users?page=1 |
https://jsonplaceholder.typicode.com/posts?userId=1Content-Type, Authorization, Accept - what are API Headers and why are they needed.
Headers are extra information sent with the request/response. Think of them as metadata.
| Header | Purpose | Example |
|---|---|---|
| Content-Type | Format of body data | application/json |
| Accept | Desired response format | application/json |
| Authorization | Authentication token | Bearer eyJ... |
| User-Agent | Client info | HttpNinja/1.0 |
| Accept-Language | Preferred language | en-US |
| Cache-Control | Caching rules | no-cache |
| Header | Purpose |
|---|---|
| Content-Type | Format of response body |
| Content-Length | Response size (bytes) |
| X-RateLimit-Remaining | Requests remaining |
| X-Request-Id | Unique request identifier |
| Set-Cookie | Set a cookie |
application/json // JSON data
application/xml // XML data
application/x-www-form-urlencoded // Form data
multipart/form-data // File upload
text/plain // Plain text
text/html // HTML
X-Custom-Header: MyValuehttps://httpbin.org/headers - view your headersCreate, Read, Update, Delete - performing all types of data operations with APIs.
CRUD = Create, Read, Update, Delete - the four basic operations on data.
| CRUD | HTTP Method | SQL | Example |
|---|---|---|---|
| Create | POST | INSERT | Create new user |
| Read | GET | SELECT | View user list |
| Update | PUT/PATCH | UPDATE | Edit user info |
| Delete | DELETE | DELETE | Remove user |
// CREATE - new user
POST /api/users
Body: {"name": "John", "email": "john@test.com"}
Response: 201 Created
// READ - all users
GET /api/users
Response: 200 OK, [{"id":1,"name":"John"}, ...]
// READ - single user
GET /api/users/1
Response: 200 OK, {"id":1,"name":"John"}
// UPDATE - edit user
PUT /api/users/1
Body: {"name": "John Updated", "email": "new@test.com"}
Response: 200 OK
// DELETE - remove user
DELETE /api/users/1
Response: 204 No Content
| PUT | PATCH |
|---|---|
| Replaces entire resource | Partial update |
| Must send all fields | Only changed fields |
| Idempotent | May not be idempotent |
https://jsonplaceholder.typicode.com/postshttps://jsonplaceholder.typicode.com/posts/1https://jsonplaceholder.typicode.com/posts/1https://jsonplaceholder.typicode.com/posts/1API Authentication, JWT, OAuth, API Security best practices
API Key, Bearer Token, Basic Auth, OAuth - how different authentication methods work.
Simple key sent in header or query param.
// In Header
GET /api/data
X-API-Key: abc123xyz
// In Query Param
GET /api/data?api_key=abc123xyz
Username:password base64 encoded.
GET /api/data
Authorization: Basic dXNlcjpwYXNzd29yZA==
// base64("user:password")
Token-based auth, usually JWT.
GET /api/data
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Third-party login (Google, Facebook, GitHub).
// Step 1: Get authorization code
// Step 2: Exchange code for access token
// Step 3: Use access token
Authorization: Bearer {access_token}
| Method | Security | Use Case |
|---|---|---|
| API Key | Low-Medium | Public APIs, simple apps |
| Basic Auth | Low | Internal APIs, development |
| Bearer/JWT | High | Most production APIs |
| OAuth 2.0 | High | Third-party integration |
What is JWT, how it works, its structure - the foundation of modern API authentication.
JWT (JSON Web Token) is a compact, URL-safe token that carries user information. It's self-contained, meaning all info is inside the token.
JWT has three parts, separated by dots (.):
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4iLCJpYXQiOjE1MTYyMzkwMjJ9.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
|___________________________________|
Header (Algorithm)
|___________________________________________|
Payload (Data)
|___________________________|
Signature
// Header
{
"alg": "HS256",
"typ": "JWT"
}
// Payload
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022,
"exp": 1516242622
}
// Signature
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)
| Claim | Full Name | Meaning |
|---|---|---|
| sub | Subject | User ID |
| iat | Issued At | When token was created |
| exp | Expiration | When token expires |
| iss | Issuer | Who issued the token |
| aud | Audience | Who the token is for |
What are API rate limits, why they exist, how to handle 429 errors.
A limit on how many API calls can be made in a certain time period. Used to prevent server overload.
HTTP/1.1 200 OK
X-RateLimit-Limit: 1000 // Total allowed
X-RateLimit-Remaining: 950 // Remaining
X-RateLimit-Reset: 1640000000 // Reset time (Unix timestamp)
HTTP/1.1 429 Too Many Requests
Retry-After: 60
{
"error": "Rate limit exceeded",
"message": "Please wait 60 seconds"
}
| API | Free Tier Limit |
|---|---|
| GitHub API | 60 requests/hour |
| Twitter API | 450 requests/15 min |
| Google Maps | 25,000/day |
Why do APIs have v1, v2 in their URLs? Best practices for API version management.
When APIs change, versioning ensures old clients don't break.
https://api.example.com/v1/users
https://api.example.com/v2/users
https://api.example.com/users?version=1
https://api.example.com/users?version=2
GET /users
Accept-Version: v1
GET /users
Accept-Version: v2
Accept: application/vnd.github.v3+json
Properly handling API errors, error response format, debugging tips.
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid email format",
"details": [
{
"field": "email",
"message": "Must be a valid email address"
}
]
},
"requestId": "req_abc123"
}
| Error | Cause | Solution |
|---|---|---|
| 401 Unauthorized | Token missing/expired | Re-login, refresh token |
| 403 Forbidden | No permission | Check user role |
| 404 Not Found | Wrong URL/ID | Check endpoint, ID |
| 422 Validation | Invalid data | Check request body |
| 429 Rate Limit | Too many requests | Wait and retry |
| 500 Server Error | Server bug | Contact API provider |
| 503 Unavailable | Server down | Wait, check status page |
Why CORS errors happen, what Access-Control headers are, how to fix them.
CORS (Cross-Origin Resource Sharing) is a security mechanism that tells the browser which domains are allowed to call an API.
Browser security: requests from one origin to another are blocked.
// Same Origin
https://example.com/page1 → https://example.com/api ✓
// Different Origin (CORS needed)
https://mysite.com → https://api.example.com ✗ (blocked)
| Header | Purpose |
|---|---|
| Access-Control-Allow-Origin | Which origins are allowed |
| Access-Control-Allow-Methods | Which methods are allowed |
| Access-Control-Allow-Headers | Which headers are allowed |
| Access-Control-Allow-Credentials | Whether cookies are allowed |
Access-Control-Allow-Origin: https://mysite.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true
CORS is only enforced in browsers. HttpNinja is a native app, so there are no CORS restrictions. That's why an API might error in browser but work fine in HttpNinja!
Getting CORS error in browser? Test the same API in HttpNinja - no CORS restrictions!
Reading alone won't teach you APIs. Test real APIs with HttpNinja - learn every concept hands-on!
Download Free - Play Store