Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

REST API & Postman Documentation

Design, build, secure and test REST APIs — HTTP methods, status codes, good URLs, pagination, auth and Postman.

A REST API lets apps talk to a server over HTTP using URLs and JSON. Nearly every web and mobile app is built on one, and API questions come up in most backend interviews. This page covers how to design APIs, how auth works, and how to test them with Postman.

1. Introduction

Term Meaning
API A defined way for programs to talk to each other
REST A style of API built on resources and HTTP
Resource A thing the API exposes, such as a student or an order
Endpoint A URL + method, e.g. GET /students/7
Request / response What the client sends / what the server returns
JSON The usual data format

REST principles:

  • Client–server: the UI and the data are separate.
  • Stateless: each request carries everything needed; the server keeps no session between calls.
  • Uniform interface: resources have URLs, and HTTP methods say what to do.
  • Cacheable: responses can say whether they may be cached.

2. Anatomy of a Request

POST /api/students HTTP/1.1
Host: example.com
Content-Type: application/json
Authorization: Bearer eyJhbGciOi...

{ "name": "Asha", "marks": 91 }
HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/students/7

{ "id": 7, "name": "Asha", "marks": 91 }
Where Used for Example
Path Which resource /students/7
Query string Filter, sort, page ?city=Delhi&page=2
Headers Metadata, auth Authorization, Accept
Body Data to create or change JSON

3. HTTP Methods

Method Use Idempotent Safe
GET Read Yes Yes
POST Create No No
PUT Replace all of a resource Yes No
PATCH Change part of it Usually not guaranteed No
DELETE Remove Yes No

Idempotent means repeating the call has the same effect as doing it once. Safe means it changes nothing.

4. Status Codes

Code Meaning When
200 OK Success Normal GET, PUT, PATCH
201 Created Created After POST
204 No Content Success, empty body After DELETE
301 / 302 Redirect Moved permanently / temporarily
304 Not Modified Use your cached copy With ETag
400 Bad Request Invalid input Malformed data
401 Unauthorized Not logged in Token missing or invalid
403 Forbidden Logged in, not allowed Wrong role
404 Not Found No such resource Wrong id
409 Conflict Clashes with current state Email already used
422 Unprocessable Valid format, failed rules Validation errors
429 Too Many Requests Rate limited Slow down
500 Internal Server Error A server bug Unhandled error
502 / 503 / 504 Upstream or availability trouble Bad gateway, unavailable, timeout

5. Designing Good URLs

GET    /students            list
POST   /students            create
GET    /students/7          read one
PATCH  /students/7          update
DELETE /students/7          delete
GET    /students/7/courses  nested resource

Rules:

  • Use nouns, not verbs: /students, not /getStudents.
  • Use plural names and lowercase, with hyphens: /course-reviews.
  • Version the API: /api/v1/students.
  • Return the same error shape everywhere:
{ "error": { "code": "VALIDATION_FAILED", "message": "Email is required", "field": "email" } }

6. Pagination, Filtering and Sorting

GET /students?city=Delhi&sort=-marks&page=2&limit=20
{
  "items": [],
  "page": 2,
  "limit": 20,
  "total": 134
}
Pagination How Good for
Offset ?page=2&limit=20 Simple lists
Cursor ?after=abc123 Large or fast-changing data

7. A REST API in Express

import express from 'express';

const app = express();
app.use(express.json());

let students = [{ id: 1, name: 'Asha', marks: 91 }];

app.get('/api/students', (req, res) => res.json(students));

app.get('/api/students/:id', (req, res) => {
  const s = students.find((x) => x.id === Number(req.params.id));
  if (!s) return res.status(404).json({ error: 'Student not found' });
  res.json(s);
});

app.post('/api/students', (req, res) => {
  const { name, marks } = req.body;
  if (!name) return res.status(400).json({ error: 'Name is required' });
  const s = { id: Date.now(), name, marks };
  students.push(s);
  res.status(201).json(s);
});

app.delete('/api/students/:id', (req, res) => {
  students = students.filter((x) => x.id !== Number(req.params.id));
  res.status(204).end();
});

app.listen(3000);

More in the Express docs and Spring Boot docs.

8. Authentication

Method How Used for
API key Secret key in a header Server-to-server
Session cookie Server stores the session Classic websites
JWT Signed token in Authorization: Bearer SPAs, mobile apps
OAuth 2.0 Log in through Google etc. Third-party access

JWT flow:

1. POST /login with email + password
2. Server checks them and returns a signed token
3. Client sends Authorization: Bearer <token> on each call
4. Server verifies the signature and expiry

A JWT is signed, not encrypted: anyone can read it, so never put passwords in it. Use short expiry times with a refresh token. More in Authentication — JWT, Sessions and Cookies.

Authentication asks who are you? Authorization asks what may you do?

9. API Security

  • Use HTTPS everywhere.
  • Validate all input on the server; never trust the client.
  • Hash passwords (bcrypt or argon2).
  • Add rate limiting (429) to stop abuse.
  • Allow only your own sites with CORS.
  • Use parameterised queries to stop SQL injection.
  • Don't leak stack traces in errors.

CORS is a browser rule: a page may only read responses from another origin if that server allows it with headers such as Access-Control-Allow-Origin.

10. Testing with Postman

  1. Create a Collection to group requests.
  2. Add a request: choose the method, enter the URL, and set Params, Headers and Body (raw → JSON).
  3. Create an Environment with variables such as baseUrl and token, and use them as {{baseUrl}}/students.
  4. Set auth once on the collection (Authorization → Bearer Token).

Save a login token automatically, in the Scripts → Post-response tab of the login request:

pm.environment.set('token', pm.response.json().token);

Write tests in the same place:

pm.test('status is 201', () => pm.response.to.have.status(201));

pm.test('has an id', () => {
  const body = pm.response.json();
  pm.expect(body).to.have.property('id');
});

pm.test('fast enough', () => pm.expect(pm.response.responseTime).to.be.below(500));

Run a whole collection with the Collection Runner, or from the terminal for CI:

npm install -g newman
newman run students.postman_collection.json -e dev.postman_environment.json

curl does the same from a terminal:

curl -X POST https://example.com/api/students \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"name":"Asha","marks":91}'

11. REST vs GraphQL vs gRPC

REST GraphQL gRPC
Data Fixed per endpoint Client chooses fields Binary (protobuf)
Endpoints Many One Methods
Good for Public APIs, most apps Complex front ends Fast service-to-service

See the GraphQL docs. Document your REST API with OpenAPI (Swagger).

12. Practice Problems

  1. Design the endpoints for a library system (books, members, loans).
  2. Build a students CRUD API with validation and correct status codes.
  3. Add JWT login and protect the write routes.
  4. Add pagination, sorting and filtering to a list endpoint.
  5. Write a Postman collection with tests for every endpoint, and run it with Newman.

13. Interview Questions

What is REST? An architectural style using resources, URLs, HTTP methods and stateless requests.

PUT vs PATCH? PUT replaces the whole resource; PATCH changes part of it.

POST vs PUT? POST creates and is not idempotent; PUT replaces at a known URL and is idempotent.

401 vs 403? 401: not authenticated. 403: authenticated but not allowed.

What does idempotent mean? Repeating the request has the same effect as sending it once.

What does stateless mean? Every request contains everything needed; the server stores no client session.

How does JWT work? The server signs a token after login; the client sends it with each call, and the server verifies it.

What is CORS? A browser rule controlling which origins may read a response.

How do you version an API? Usually in the path (/v1/), or with a header.

How would you handle rate limiting? Count requests per user or IP and return 429, often with Retry-After.

14. Cheat Sheet & References

Methods

GET read · POST create · PUT replace · PATCH update · DELETE remove
Idempotent: GET, PUT, DELETE

Status codes

200 OK · 201 Created · 204 No Content
400 Bad Request · 401 Unauthorized · 403 Forbidden · 404 Not Found · 409 Conflict
422 Validation · 429 Too Many Requests
500 Server Error · 502 Bad Gateway · 503 Unavailable · 504 Timeout

Postman tests

pm.test('ok', () => pm.response.to.have.status(200));
pm.expect(pm.response.json()).to.have.property('id');
pm.environment.set('token', pm.response.json().token);

curl

curl https://api.site.com/items
curl -X POST url -H "Content-Type: application/json" -d '{"a":1}'
curl -H "Authorization: Bearer $TOKEN" url

References