Table of Contents:
What is REST API?
A REST API (Representational State Transfer) is a web architecture principle that allows systems to communicate using HTTP methods and resources (URLs). It’s lightweight, stateless, and widely used for connecting mobile apps, web applications, and cloud services.
For example, when your mobile app fetches user data from a server — it’s making a REST API call.
Core Principles of REST API
| Principle | Description |
|---|---|
| Statelessness | Every request is independent; the server stores no client context. |
| Client-Server Architecture | Separation of UI (client) and data storage (server). |
| Cacheable | Responses can be stored and reused. |
| Uniform Interface | Standardized method of communication using HTTP. |
| Layered System | APIs can have multiple layers (gateway, authentication, etc.). |
| Resource-Based URLs | Each endpoint represents a unique resource (like /users or /posts). |
Common HTTP Methods in REST API
| Method | Purpose | Example Endpoint | Operation |
|---|---|---|---|
| GET | Retrieve data | /api/users | Read |
| POST | Create new data | /api/users | Create |
| PUT | Replace existing data | /api/users/1 | Update |
| PATCH | Update partial data | /api/users/1 | Partial Update |
| DELETE | Remove data | /api/users/1 | Delete |
rest api cheatsheet, rest api tutorial, rest api methods, rest api examples, restful api design, api authentication, http status codes, json response, crud operations api, api development guide, api endpoints
REST API Example Structure
GET /api/products → Fetch all products
GET /api/products/10 → Fetch a specific product
POST /api/products → Add a new product
PUT /api/products/10 → Update product details
DELETE /api/products/10 → Delete product
Example: REST API Call using JavaScript Fetch
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error fetching data:', error));
POST Example:
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
title: 'Learning REST API',
body: 'This is a RESTful example',
userId: 5
})
})
.then(response => response.json())
.then(data => console.log('Created:', data));
PHP REST API Example
<?php
$apiURL = "https://jsonplaceholder.typicode.com/posts";
$data = array("title" => "New Post", "body" => "Learning REST API", "userId" => 10);
$options = array(
"http" => array(
"header" => "Content-Type: application/json\r\n",
"method" => "POST",
"content" => json_encode($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($apiURL, false, $context);
echo $result;
?>
Node.js REST API Example
const express = require('express');
const app = express();
app.use(express.json());
let users = [{ id: 1, name: "Alice" }];
app.get('/api/users', (req, res) => res.json(users));
app.post('/api/users', (req, res) => {
const newUser = { id: users.length + 1, name: req.body.name };
users.push(newUser);
res.status(201).json(newUser);
});
app.listen(3000, () => console.log('Server running on port 3000'));
Python REST API Example
from flask import Flask, jsonify, request
app = Flask(__name__)
users = [{"id": 1, "name": "Alice"}]
@app.route("/api/users", methods=["GET"])
def get_users():
return jsonify(users)
@app.route("/api/users", methods=["POST"])
def add_user():
new_user = request.json
users.append(new_user)
return jsonify(new_user), 201
if __name__ == "__main__":
app.run(debug=True)
HTTP Response Codes Reference Table
| Code | Meaning | Example Scenario |
|---|---|---|
| 200 OK | Successful request | Data fetched successfully |
| 201 Created | Resource created | User registration successful |
| 400 Bad Request | Invalid data | Missing parameter in request |
| 401 Unauthorized | Authentication failed | Invalid API token |
| 403 Forbidden | No permission | Access denied |
| 404 Not Found | Resource missing | User ID not found |
| 500 Internal Server Error | Server issue | API crashed unexpectedly |
REST API Authentication Techniques
| Type | Usage | Example |
|---|---|---|
| API Key | Simple, used in header or query | ?apikey=123456 |
| Bearer Token (JWT) | Modern authentication | Authorization: Bearer TOKEN |
| OAuth 2.0 | Third-party authentication | Used by Google, GitHub APIs |
| Basic Auth | Encoded username/password | Authorization: Basic base64string |
Working with JSON in REST APIs
Convert JavaScript object to JSON:
const obj = { name: "Bob", age: 25 };
console.log(JSON.stringify(obj));
Parse JSON response:
let json = '{"status":"success"}';
let data = JSON.parse(json);
console.log(data.status);
REST API CRUD Operations Cheatsheet
| Operation | HTTP Method | Endpoint Example |
|---|---|---|
| Create | POST | /api/posts |
| Read | GET | /api/posts |
| Update | PUT / PATCH | /api/posts/1 |
| Delete | DELETE | /api/posts/1 |
REST API Best Practices
✅ Use HTTPS for all API calls
✅ Keep endpoints noun-based (/users, /products)
✅ Use versioning (/api/v1/...)
✅ Handle errors gracefully with clear JSON responses
✅ Document APIs using Swagger or Postman
✅ Test using curl, Postman, or Insomnia
FAQ — REST API Cheatsheet
Q1. What does REST stand for?
REST means Representational State Transfer, a standard way for systems to exchange data over HTTP.
Q2. What’s the difference between REST and SOAP APIs?
REST is lightweight and uses JSON, while SOAP uses XML and more strict messaging protocols.
Q3. How do I test a REST API?
You can use Postman, curl, or built-in browser tools to send and inspect requests.
Q4. What is an endpoint in REST API?
An endpoint is a specific URL where an API can be accessed — e.g., /api/products/1.
Q5. Can REST API return XML instead of JSON?
Yes. Though JSON is standard, you can configure REST APIs to return XML responses if needed.

