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 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 Cheatsheet — Learn RESTful API Architecture, HTTP Methods, and JSON Requests

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

PrincipleDescription
StatelessnessEvery request is independent; the server stores no client context.
Client-Server ArchitectureSeparation of UI (client) and data storage (server).
CacheableResponses can be stored and reused.
Uniform InterfaceStandardized method of communication using HTTP.
Layered SystemAPIs can have multiple layers (gateway, authentication, etc.).
Resource-Based URLsEach endpoint represents a unique resource (like /users or /posts).

Common HTTP Methods in REST API

MethodPurposeExample EndpointOperation
GETRetrieve data/api/usersRead
POSTCreate new data/api/usersCreate
PUTReplace existing data/api/users/1Update
PATCHUpdate partial data/api/users/1Partial Update
DELETERemove data/api/users/1Delete
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

CodeMeaningExample Scenario
200 OKSuccessful requestData fetched successfully
201 CreatedResource createdUser registration successful
400 Bad RequestInvalid dataMissing parameter in request
401 UnauthorizedAuthentication failedInvalid API token
403 ForbiddenNo permissionAccess denied
404 Not FoundResource missingUser ID not found
500 Internal Server ErrorServer issueAPI crashed unexpectedly

REST API Authentication Techniques

TypeUsageExample
API KeySimple, used in header or query?apikey=123456
Bearer Token (JWT)Modern authenticationAuthorization: Bearer TOKEN
OAuth 2.0Third-party authenticationUsed by Google, GitHub APIs
Basic AuthEncoded username/passwordAuthorization: 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

OperationHTTP MethodEndpoint Example
CreatePOST/api/posts
ReadGET/api/posts
UpdatePUT / PATCH/api/posts/1
DeleteDELETE/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.

Related Article
Machine Learning Cheatsheet (Unsupervised & Reinforcement Learning)

Machine Learning (ML) is a crucial part of artificial intelligence, enabling systems to automatically learn from data.This Machine Learning Cheatsheet Read more

HTML Cheat Sheet — Reference Guide to HTML Tags, Attributes, and Examples

HTML cheat sheet, HTML tags reference, HTML attributes list, HTML examples for beginners, semantic HTML guide, HTML forms tutorial, HTML Read more

Python Cheat Sheet — Complete Syntax Reference and Programming Examples

This Python Cheat Sheet is your quick reference guide for writing efficient Python code. Whether you’re preparing for coding interviews, Read more

PHP Cheat Sheet — Complete Syntax Reference and Programming Examples for Beginners

PHP Cheat Sheet — Complete Syntax Reference & Examples This PHP Cheat Sheet serves as a quick, structured reference for Read more

JavaScript Cheat Sheet — Complete ES6 Syntax, Functions, and DOM Methods with Examples

JavaScript Cheat Sheet — Complete Syntax Reference & Examples JavaScript is the core scripting language of the web, enabling interactivity, Read more

CSS Cheat Sheet — Complete CSS3 Selectors, Properties, and Layout Examples

CSS Cheat Sheet — Complete CSS3 Syntax, Selectors & Layout Examples Cascading Style Sheets (CSS) is the language used to Read more

Java Cheat Sheet — Complete Java Syntax, Data Types, Loops, and OOP Concepts for Beginners

Java Cheat Sheet — Complete Java Syntax, Classes, and Examples Java is a powerful, object-oriented programming language widely used for Read more

HTML5 Cheat Sheet — Complete Tag Reference & Examples

HTML5 is the core markup language of the modern web, used to structure content such as text, images, forms, and Read more

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments