Get App - Free

API - Complete Learning Guide

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 API REST API API Authentication JSON API Testing

Google Search Keywords - Use these terms to find more resources

What is API
API explained simple
REST API basics
What is RESTful API
API vs REST API
How API works
API for beginners
API request response
JSON API tutorial
API authentication methods
API key vs Bearer token
REST API best practices
API endpoint explained
CRUD API operations
API status codes
Postman API testing
1

Beginner - API Fundamentals

What is an API and why do you need it - starting from the basics

Beginner

What is API?

API (Application Programming Interface) explained - what it is and why it's so important. Illustrated with real-life examples.

what is API API meaning API explained

What is an API?

API (Application Programming Interface) is a bridge or medium that allows two software applications to communicate with each other.

Real-Life Example: Restaurant

Imagine you're at a restaurant:

  • You (Client) - the one placing an order
  • Waiter (API) - takes your order to the kitchen
  • Kitchen (Server) - where the food is prepared

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!

Tech Example

When you open a Weather app:

  1. App sends a request to the weather server (API call)
  2. Server returns weather data for your location (API response)
  3. App displays that data
// API Request Example
GET https://api.weather.com/current?city=London

// API Response Example
{
  "city": "London",
  "temperature": "18°C",
  "condition": "Cloudy"
}

Why Do We Need APIs?

ReasonExplanation
Data AccessAccess others' data (weather, maps, payment)
SecurityNo direct database access, controlled access via API
ReusabilityBuild once, use in many apps
ScalabilityFrontend and Backend stay separate, easy to scale

Try in HttpNinja

  1. Open HttpNinja app
  2. Enter URL: https://httpbin.org/get
  3. Method: GET
  4. Tap Send button
  5. View the response - this is your first API call!
Beginner

What is REST API?

REST (Representational State Transfer) explained - why most modern APIs follow this architecture.

REST API RESTful API REST principles

What is REST?

REST (Representational State Transfer) is an architectural style - a set of rules or patterns for building APIs.

Core REST Principles

PrincipleMeaning
StatelessEach request is independent, server doesn't remember previous requests
Client-ServerFrontend and Backend are separated
Uniform InterfaceUses standard HTTP methods (GET, POST, PUT, DELETE)
CacheableResponses can be cached for better performance

REST API URL Structure

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

HTTP Methods in REST

MethodPurposeExample
GETRetrieve data (Read)GET /users - get all users
POSTCreate new data (Create)POST /users - create new user
PUTUpdate entire data (Update)PUT /users/1 - update user 1
DELETERemove data (Delete)DELETE /users/1 - delete user 1

Try in HttpNinja

  1. GET request: https://jsonplaceholder.typicode.com/users
  2. POST request: https://jsonplaceholder.typicode.com/posts
  3. In Body tab add JSON: {"title": "Test", "body": "Hello"}
Beginner

API vs REST API - Difference

What's the difference between API and REST API? Many get confused - this clears it up.

API vs REST API difference comparison

Simple Answer

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!

Different Types of APIs

TypeWhat It IsUse Case
REST APIHTTP-based, JSON responseMost web/mobile apps
SOAP APIXML-based, strict rulesBanking, Enterprise
GraphQL APIQuery language, flexibleFacebook, GitHub
WebSocket APIReal-time, bidirectionalChat, Gaming
RPC APIRemote procedure callsInternal services

Why is REST API Most Popular?

  • Simple - Uses HTTP methods
  • Flexible - Supports JSON, XML, any format
  • Scalable - Stateless nature makes it easy to scale
  • Universal - Works with all languages/platforms
// REST API - Simple JSON
GET /api/users/1
Response: {"id": 1, "name": "John"}

// SOAP API - Complex XML

  
    
      1
    
  
Beginner

API Request & Response

What gets sent in an API call (Request) and what comes back (Response) - detailed breakdown.

API request API response request body

Parts of an API Request

PartWhat It ContainsExample
URL/EndpointWhere the request goeshttps://api.example.com/users
MethodWhat action to performGET, POST, PUT, DELETE
HeadersExtra informationAuthorization, Content-Type
BodyData being sent (POST/PUT){"name": "John"}
Query ParamsFilter/options?page=1&limit=10

Complete Request Example

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
}

Parts of an API Response

PartWhat It ContainsExample
Status CodeIndicates success/error200, 201, 400, 404, 500
HeadersResponse metadataContent-Type, Cache-Control
BodyActual dataJSON/XML data

Complete Response Example

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"
}

Try in HttpNinja

  1. Send request to: https://httpbin.org/post (POST method)
  2. Add custom headers in Headers tab
  3. Add JSON data in Body tab
  4. See your data echoed back in the response
2

Intermediate - Core Concepts

Important API concepts - JSON, Status Codes, Headers

Intermediate

JSON - API Data Format

JSON (JavaScript Object Notation) - the standard format for sending and receiving data in APIs.

JSON format JSON syntax parse JSON

What is JSON?

JSON (JavaScript Object Notation) is a data format that is both human-readable and machine-parseable. Almost all APIs use JSON.

JSON Syntax

{
  "string": "Hello World",
  "number": 123,
  "decimal": 45.67,
  "boolean": true,
  "null": null,
  "array": [1, 2, 3],
  "object": {
    "nested": "value"
  }
}

JSON Rules

  • Keys must be in double quotes: "name"
  • Strings must be in double quotes: "Hello"
  • No trailing commas allowed
  • No comments allowed in JSON

Common JSON in APIs

// 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 vs XML

JSONXML
LightweightVerbose
Easy to readMore complex
Native to JavaScriptNeeds parsing
Modern APIsLegacy/Enterprise

Try in HttpNinja

  1. GET: https://jsonplaceholder.typicode.com/users/1
  2. View formatted JSON in the response
  3. POST your own JSON data
Intermediate

HTTP Status Codes

200 OK, 404 Not Found, 500 Error - what do status codes in API responses mean.

status codes 200 OK 404 error

Status Code Categories

RangeCategoryMeaning
1xxInformationalProcessing in progress
2xxSuccessEverything is OK
3xxRedirectionNeed to go elsewhere
4xxClient ErrorYour mistake
5xxServer ErrorServer's problem

Common Status Codes

CodeNameWhen It Occurs
200OKRequest successful (GET/PUT)
201CreatedNew resource created (POST)
204No ContentSuccess but no body (DELETE)
400Bad RequestInvalid data sent
401UnauthorizedNot logged in
403ForbiddenNo permission
404Not FoundResource doesn't exist
422UnprocessableValidation error
429Too Many RequestsRate limit exceeded
500Internal ErrorServer crashed
502Bad GatewayProxy/Gateway error
503Service UnavailableServer down/maintenance

Error Response Example

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Email is required",
    "field": "email"
  }
}

Try in HttpNinja

  1. https://httpbin.org/status/200 - Success
  2. https://httpbin.org/status/404 - Not Found
  3. https://httpbin.org/status/500 - Server Error
Intermediate

API Endpoints & URLs

What is an API Endpoint, how URL structure works, what are Query Parameters.

API endpoint query params URL structure

What is an API Endpoint?

An endpoint is a specific URL where an API request is sent. Each endpoint performs a specific function.

URL Structure

https://api.example.com/v1/users?page=1&limit=10
|_____|  |_____________| |_| |___| |______________|
  |           |          |    |          |
Protocol    Host      Version Path   Query Params

RESTful URL Design

MethodEndpointAction
GET/usersGet all users
GET/users/123Get user by ID
POST/usersCreate new user
PUT/users/123Update user
DELETE/users/123Delete user
GET/users/123/postsGet user's posts

Query Parameters

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

Path Parameters vs Query Parameters

TypeUse CaseExample
Path ParamSpecific resource/users/123
Query ParamFilter, sort, page/users?page=1

Try in HttpNinja

  1. Use the Params tab to add query parameters
  2. Try: https://jsonplaceholder.typicode.com/posts?userId=1
Intermediate

HTTP Headers

Content-Type, Authorization, Accept - what are API Headers and why are they needed.

HTTP headers Content-Type Authorization

What are Headers?

Headers are extra information sent with the request/response. Think of them as metadata.

Common Request Headers

HeaderPurposeExample
Content-TypeFormat of body dataapplication/json
AcceptDesired response formatapplication/json
AuthorizationAuthentication tokenBearer eyJ...
User-AgentClient infoHttpNinja/1.0
Accept-LanguagePreferred languageen-US
Cache-ControlCaching rulesno-cache

Common Response Headers

HeaderPurpose
Content-TypeFormat of response body
Content-LengthResponse size (bytes)
X-RateLimit-RemainingRequests remaining
X-Request-IdUnique request identifier
Set-CookieSet a cookie

Content-Type Values

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

Try in HttpNinja

  1. Go to Headers tab
  2. Add custom header: X-Custom-Header: MyValue
  3. https://httpbin.org/headers - view your headers
Intermediate

CRUD Operations

Create, Read, Update, Delete - performing all types of data operations with APIs.

CRUD Create Read Update Delete REST CRUD

What is CRUD?

CRUD = Create, Read, Update, Delete - the four basic operations on data.

CRUD to HTTP Mapping

CRUDHTTP MethodSQLExample
CreatePOSTINSERTCreate new user
ReadGETSELECTView user list
UpdatePUT/PATCHUPDATEEdit user info
DeleteDELETEDELETERemove user

Complete CRUD Example

// 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 vs PATCH

PUTPATCH
Replaces entire resourcePartial update
Must send all fieldsOnly changed fields
IdempotentMay not be idempotent

Try in HttpNinja

  1. POST: https://jsonplaceholder.typicode.com/posts
  2. GET: https://jsonplaceholder.typicode.com/posts/1
  3. PUT: https://jsonplaceholder.typicode.com/posts/1
  4. DELETE: https://jsonplaceholder.typicode.com/posts/1
3

Advanced - Authentication & Security

API Authentication, JWT, OAuth, API Security best practices

Advanced

API Authentication Methods

API Key, Bearer Token, Basic Auth, OAuth - how different authentication methods work.

API authentication API key Bearer token

Why is Authentication Needed?

  • Control API access
  • Identify users
  • Apply rate limiting
  • Billing/Usage tracking

Authentication Methods

1. API Key

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

2. Basic Authentication

Username:password base64 encoded.

GET /api/data
Authorization: Basic dXNlcjpwYXNzd29yZA==
// base64("user:password")

3. Bearer Token

Token-based auth, usually JWT.

GET /api/data
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

4. OAuth 2.0

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}

Comparison

MethodSecurityUse Case
API KeyLow-MediumPublic APIs, simple apps
Basic AuthLowInternal APIs, development
Bearer/JWTHighMost production APIs
OAuth 2.0HighThird-party integration

Try in HttpNinja

  1. Go to Auth tab
  2. Select Bearer Token
  3. Paste your token
  4. HttpNinja automatically adds the header
Advanced

JWT (JSON Web Token)

What is JWT, how it works, its structure - the foundation of modern API authentication.

JWT token JSON Web Token JWT structure

What is JWT?

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 Structure

JWT has three parts, separated by dots (.):

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4iLCJpYXQiOjE1MTYyMzkwMjJ9.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

|___________________________________|
         Header (Algorithm)

                                    |___________________________________________|
                                              Payload (Data)

                                                                                 |___________________________|
                                                                                       Signature

JWT Parts Decoded

// Header
{
  "alg": "HS256",
  "typ": "JWT"
}

// Payload
{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022,
  "exp": 1516242622
}

// Signature
HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secret
)

Common JWT Claims

ClaimFull NameMeaning
subSubjectUser ID
iatIssued AtWhen token was created
expExpirationWhen token expires
issIssuerWho issued the token
audAudienceWho the token is for

JWT Flow

  1. User logs in (email/password)
  2. Server generates JWT
  3. Client saves JWT (localStorage/cookie)
  4. JWT sent with every API call
  5. Server verifies JWT

Try in HttpNinja

  1. Auth tab > Bearer Token
  2. Paste your JWT
  3. HttpNinja decodes and shows JWT contents
Advanced

Rate Limiting & Throttling

What are API rate limits, why they exist, how to handle 429 errors.

rate limiting 429 error API throttling

What is Rate Limiting?

A limit on how many API calls can be made in a certain time period. Used to prevent server overload.

Common Rate Limit Headers

HTTP/1.1 200 OK
X-RateLimit-Limit: 1000        // Total allowed
X-RateLimit-Remaining: 950     // Remaining
X-RateLimit-Reset: 1640000000  // Reset time (Unix timestamp)

429 Too Many Requests

HTTP/1.1 429 Too Many Requests
Retry-After: 60

{
  "error": "Rate limit exceeded",
  "message": "Please wait 60 seconds"
}

Rate Limit Examples

APIFree Tier Limit
GitHub API60 requests/hour
Twitter API450 requests/15 min
Google Maps25,000/day

How to Handle

  • Check remaining limit before calls
  • Implement exponential backoff
  • Cache responses when possible
  • Use webhooks instead of polling
Advanced

API Versioning

Why do APIs have v1, v2 in their URLs? Best practices for API version management.

API versioning API v1 v2 breaking changes

Why Versioning?

When APIs change, versioning ensures old clients don't break.

Versioning Strategies

1. URL Path Versioning (Most Common)

https://api.example.com/v1/users
https://api.example.com/v2/users

2. Query Parameter

https://api.example.com/users?version=1
https://api.example.com/users?version=2

3. Header Versioning

GET /users
Accept-Version: v1

GET /users
Accept-Version: v2

4. Accept Header (GitHub style)

Accept: application/vnd.github.v3+json

When to Create New Version

  • Breaking changes (field removed, renamed)
  • Response structure change
  • Authentication method change
  • Major functionality change

Best Practices

  • URL versioning is most clear
  • Deprecate old versions, don't remove suddenly
  • Maintain a changelog
  • Use Sunset header to announce deprecation
Advanced

API Error Handling

Properly handling API errors, error response format, debugging tips.

API error handling error response debugging API

Good Error Response Format

{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid email format",
    "details": [
      {
        "field": "email",
        "message": "Must be a valid email address"
      }
    ]
  },
  "requestId": "req_abc123"
}

Common API Errors & Solutions

ErrorCauseSolution
401 UnauthorizedToken missing/expiredRe-login, refresh token
403 ForbiddenNo permissionCheck user role
404 Not FoundWrong URL/IDCheck endpoint, ID
422 ValidationInvalid dataCheck request body
429 Rate LimitToo many requestsWait and retry
500 Server ErrorServer bugContact API provider
503 UnavailableServer downWait, check status page

Debugging Tips

  • Read response body carefully
  • Check request headers
  • Verify Content-Type is correct
  • Check API documentation
  • Export cURL command and test in terminal

Debug in HttpNinja

  1. See color-coded status in error responses
  2. Check response headers
  3. Verify sent data in Request tab
Advanced

CORS - Cross-Origin Requests

Why CORS errors happen, what Access-Control headers are, how to fix them.

CORS cross origin CORS error

What is CORS?

CORS (Cross-Origin Resource Sharing) is a security mechanism that tells the browser which domains are allowed to call an API.

Same Origin Policy

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)

CORS Headers

HeaderPurpose
Access-Control-Allow-OriginWhich origins are allowed
Access-Control-Allow-MethodsWhich methods are allowed
Access-Control-Allow-HeadersWhich headers are allowed
Access-Control-Allow-CredentialsWhether cookies are allowed

Server Response Example

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

Why No CORS in HttpNinja?

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!

CORS-Free Testing in HttpNinja

Getting CORS error in browser? Test the same API in HttpNinja - no CORS restrictions!

Practice with HttpNinja

Reading alone won't teach you APIs. Test real APIs with HttpNinja - learn every concept hands-on!

Download Free - Play Store
All HTTP Methods (GET, POST, PUT, DELETE...)
JWT, Bearer, OAuth Authentication
JSON Formatter & Syntax Highlighting
Request History & Collections
100% Free - No Ads - Offline

More Google Search Keywords for Learning

build REST API Node.js
REST API Python Flask
API testing tutorial
Postman API tutorial
API documentation Swagger
GraphQL vs REST
API security best practices
OAuth 2.0 tutorial
API gateway explained
microservices API design
REST API interview questions
API rate limiting implementation