🚀 Cyber Security New Batch Start from 1 JunEnroll Now
Cyber Defence
Development

API Development Tutorial: REST API Basics for Beginners 2026

Complete API development tutorial for beginners. Learn REST API basics in 2026 — HTTP methods, endpoints, authentication, data handling, and building real APIs with Node.js and Express with practical examples.

Amit Kumar
Amit KumarEthical Hacker & Founder
7 min read

API Development Tutorial: REST API Basics for Beginners 2026

API (Application Programming Interface) development modern web development ka essential skill hai. Yeh complete tutorial aapko REST API fundamentals se lekar building production-ready APIs tak le jayega with practical examples.

API Kya Hai

API do software applications ke beech communication ka bridge hai. Aap browser ya mobile app se request bhejein, server par processing ho, aur response wapas aye — yeh sab API ke through hota hai.

Real-world example:

  • Zomato app → API → Restaurant's server (menu, prices)
  • Your app → API → Payment gateway (transactions)
  • Weather app → API → Weather service (forecasts)

REST API Fundamentals

REST (Representational State Transfer) web services build karne ka most popular architecture hai.

REST Principles

  1. Client-Server Architecture: Client aur server independently evolve kar sakte hain
  2. Stateless: Har request mein complete information hoti hai
  3. Cacheable: Responses ko cache kiya ja sakta hai
  4. Uniform Interface: Consistent URL patterns aur HTTP methods
  5. Layered System: Architecture layers mein organized hota hai

HTTP Methods

GET - Retrieve data: GET /users

POST - Create new resource: POST /users

PUT - Update entire resource: PUT /users/123

PATCH - Partial update: PATCH /users/123

DELETE - Remove resource: DELETE /users/123

HTTP Status Codes

2xx - Success:

200 OK - Request successful

201 Created - Resource created

204 No Content - Success with no response body

4xx - Client Errors:

400 Bad Request - Invalid input

401 Unauthorized - Authentication required

403 Forbidden - No permission

404 Not Found - Resource doesn't exist

422 Unprocessable Entity - Validation failed

5xx - Server Errors:

500 Internal Server Error - Something broke

502 Bad Gateway - Upstream server issue

503 Service Unavailable - Server down

REST API URL Structure

Best Practices for URL Design

Good URL Patterns:

GET /users - List all users

GET /users/123 - Get single user

POST /users - Create new user

PUT /users/123 - Update user

DELETE /users/123 - Delete user

GET /users/123/orders - Get user's orders

POST /users/123/orders - Create order for user

GET /products?category=electronics&sort=price_asc

GET /products?page=2&limit=20

Avoid: /getUsers (use GET /users), /createUser (use POST /users)

Node.js + Express API Setup Tutorial

Project Setup

Initialize project:

mkdir my-api

cd my-api

npm init -y

Install dependencies:

npm install express cors helmet morgan dotenv

npm install -D nodemon

Project structure:

mkdir src

touch src/index.js

Basic Express Server

src/index.js:

import express from 'express';

import cors from 'cors';

import helmet from 'helmet';

import morgan from 'morgan';

import dotenv from 'dotenv';

dotenv.config();

const app = express();

const PORT = process.env.PORT || 3000;

// Middleware

app.use(helmet()); // Security headers

app.use(cors()); // Enable CORS

app.use(morgan('dev')); // Request logging

app.use(express.json()); // Parse JSON bodies

app.use(express.urlencoded({ extended: true }));

// Health check route

app.get('/health', (req, res) => {

res.json({

status: 'ok',

timestamp: new Date().toISOString(),

uptime: process.uptime()

});

});

// Routes

app.use('/api/users', userRoutes);

app.use('/api/products', productRoutes);

// 404 handler

app.use((req, res) => {

res.status(404).json({

error: 'Not Found',

message: 'Route ' + req.method + ' ' + req.path + ' not found'

});

});

// Error handler

app.use((err, req, res, next) => {

console.error('Error:', err.message);

res.status(err.status || 500).json({

error: err.message || 'Internal Server Error',

});

});

app.listen(PORT, () => {

console.log('Server running on http://localhost:' + PORT);

});

REST API CRUD Operations Tutorial

In-Memory Data Store (For Learning)

src/data/users.js:

let users = [

{ id: 1, name: 'Alice Johnson', email: 'alice@example.com', role: 'admin', createdAt: new Date('2024-01-15') },

{ id: 2, name: 'Bob Smith', email: 'bob@example.com', role: 'user', createdAt: new Date('2024-02-20') }

];

export default users;

User Routes - Complete CRUD

GET /api/users - List all users:

router.get('/', (req, res) => {

const { page = 1, limit = 10, role, search } = req.query;

let filteredUsers = [...users];

if (role) filteredUsers = filteredUsers.filter(u => u.role === role);

if (search) {

const searchLower = search.toLowerCase();

filteredUsers = filteredUsers.filter(u => u.name.toLowerCase().includes(searchLower) || u.email.toLowerCase().includes(searchLower));

}

const startIndex = (page - 1) * limit;

const endIndex = startIndex + parseInt(limit);

const paginatedUsers = filteredUsers.slice(startIndex, endIndex);

res.json({ data: paginatedUsers, meta: { total: filteredUsers.length, page: parseInt(page), limit: parseInt(limit), pages: Math.ceil(filteredUsers.length / limit) } });

});

GET /api/users/:id - Get single user:

router.get('/:id', (req, res) => {

const user = users.find(u => u.id === parseInt(req.params.id));

if (!user) return res.status(404).json({ error: 'Not Found', message: 'User not found' });

res.json({ data: user });

});

POST /api/users - Create new user:

router.post('/', (req, res) => {

const { name, email, role = 'user' } = req.body;

if (!name || !email) return res.status(400).json({ error: 'Validation Error', message: 'Name and email are required' });

if (users.find(u => u.email === email)) return res.status(409).json({ error: 'Conflict', message: 'Email already exists' });

const newUser = { id: users.length ? Math.max(...users.map(u => u.id)) + 1 : 1, name, email, role, createdAt: new Date() };

users.push(newUser);

res.status(201).json({ message: 'User created successfully', data: newUser });

});

PUT /api/users/:id - Update user:

router.put('/:id', (req, res) => {

const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));

if (userIndex === -1) return res.status(404).json({ error: 'Not Found', message: 'User not found' });

const { name, email, role } = req.body;

users[userIndex] = { ...users[userIndex], ...(name && { name }), ...(email && { email }), ...(role && { role }), updatedAt: new Date() };

res.json({ message: 'User updated successfully', data: users[userIndex] });

});

DELETE /api/users/:id - Delete user:

router.delete('/:id', (req, res) => {

const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));

if (userIndex === -1) return res.status(404).json({ error: 'Not Found', message: 'User not found' });

const deletedUser = users.splice(userIndex, 1)[0];

res.json({ message: 'User deleted successfully', data: deletedUser });

});

API Authentication Tutorial

Basic Auth Middleware

API Key authentication:

export function apiKeyAuth(req, res, next) {

const apiKey = req.headers['x-api-key'];

if (!apiKey) return res.status(401).json({ error: 'Unauthorized', message: 'API key required' });

const validApiKeys = process.env.API_KEYS?.split(',') || [];

if (!validApiKeys.includes(apiKey)) return res.status(403).json({ error: 'Forbidden', message: 'Invalid API key' });

next();

}

JWT authentication:

export function jwtAuth(req, res, next) {

const authHeader = req.headers['authorization'];

if (!authHeader || !authHeader.startsWith('Bearer ')) return res.status(401).json({ error: 'Unauthorized', message: 'JWT token required' });

const token = authHeader.split(' ')[1];

try {

// Verify JWT token here

next();

} catch (error) {

return res.status(401).json({ error: 'Unauthorized', message: 'Invalid or expired token' });

}

}

REST API Best Practices

Request/Response Format

Success response:

{ "data": { ... }, "meta": { "timestamp": "2024-01-15T10:30:00Z", "requestId": "req_abc123" } }

Error response:

{ "error": "Validation Error", "message": "Email is required", "details": [{ "field": "email", "message": "Email is required" }], "meta": { "timestamp": "2024-01-15T10:30:00Z", "requestId": "req_abc123" } }

Pagination response:

{ "data": [ ... ], "meta": { "total": 100, "page": 1, "limit": 10, "pages": 10, "hasNext": true, "hasPrev": false } }

Security Best Practices

  1. Input validation - Always validate inputs
  2. Rate limiting - Prevent abuse
  3. CORS - Configure properly
  4. HTTPS - Use TLS
  5. Security headers - Use helmet
  6. SQL injection prevention - Use parameterized queries
  7. XSS prevention - Sanitize outputs
  8. Don't expose sensitive data in responses

Cyber Defence API Development Course

Cyber Defence mein REST API development ka complete course available hai jo Node.js, Express, aur database integration cover karta hai. Real-world API projects ke saath practical training.

FAQs

REST aur GraphQL mein kya farak hai?

REST fixed endpoints use karta hai, GraphQL single endpoint use karta hai jahan client specify karta hai ki kya data chahiye. REST simpler hai, GraphQL flexible data fetching deta hai.

Kya API development ke liye authentication zaroori hai?

Haan, public APIs ke liye bhi rate limiting aur basic security zaroori hai. Private APIs ke liye JWT, API keys, ya OAuth use karte hain.

Postman kya hai?

Postman API testing ka tool hai jo requests build karne, test karne, aur documentation maintain karne ke liye use hota hai.

REST API performance kaise improve karein?

Pagination implement karein, caching use karein, database queries optimize karein, compression enable karein, aur unnecessary data return na karein.

Talk to a Cyber Defence Expert

Get a free consultation on cybersecurity, training and certifications. Our team responds within 10 minutes during business hours.