REST APIs and Authentication Tutorial
Learn REST APIs and Authentication step by step: 39 lessons in 9 chapters with examples, quizzes, diagrams and projects.
Start learning →
of lessons completed
HTTP and REST Fundamentals
- What Is a REST API? Learn what an API is, what makes an HTTP API RESTful, the six REST constraints, the Richardson maturity model and how REST compares with RPC and GraphQL.
- HTTP Requests and Responses See what an HTTP message really looks like: request line, headers, body, status line, URL parts and how fetch maps to the raw text on the wire.
- HTTP Methods and Idempotency Learn what GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS mean in a REST API, what safe and idempotent methods are and why retries depend on them.
- HTTP Status Codes for APIs Learn which HTTP status code to return from a REST API: 2xx success, 3xx redirects, 4xx client errors and 5xx server errors, with a decision guide and runnable examples.
- Headers and Content Negotiation Learn the HTTP headers every API developer needs: Content-Type, Accept, content negotiation, Cache-Control, ETag and conditional requests, CORS and custom headers.
Designing Resources and Endpoints
- Resource Naming and URL Design Design clean REST URLs: use plural nouns, no verbs, sensible hierarchy, kebab-case, stable identifiers and slugs, with a URL linter and a route matcher to try.
- Designing JSON Payloads Design consistent JSON for your REST API: naming style, dates, money, IDs, null versus missing fields, enums, envelopes and how to hide internal fields.
- Filtering, Sorting and Query Parameters Design query parameters for REST collections: filters, search, sorting with a safe whitelist, sparse fieldsets and limits, with a runnable server and parser.
- Designing Error Responses Design useful REST API errors: consistent JSON, application/problem+json (RFC 9457), validation error lists, error codes, request ids and not leaking internals.
- Relationships, Sub-resources and Actions Model relationships in a REST API: nested versus flat URLs, sub-resources, embedding with include, actions that do not fit CRUD, bulk operations and async jobs.
Building an API
- Building an HTTP Server from Scratch Build a JSON API with Node's built-in http module: request and response objects, reading the body safely, sending JSON, status codes, and why frameworks exist.
- Building a Router Replace if-chains with a route table: path parameters, method matching, automatic 404 and 405 with Allow headers, route groups and a reusable mini router in Node.js.
- CRUD with an In-Memory Store Implement a complete CRUD REST API for tasks with correct status codes, Location headers, PUT versus PATCH (JSON merge patch), 404s and a client that exercises every route.
- Validation and Input Handling Validate API input properly: type and range checks, required and unknown fields, trimming, mass assignment, size limits, 400 versus 422 and a tiny reusable schema validator.
- Middleware and Error Handling Build a middleware pipeline for a REST API: logging, request ids, CORS, body parsing, auth guards, async errors, a central error handler and a 404 fallback.
Authentication Basics
- Authentication vs Authorization Understand authentication (who are you) versus authorization (what may you do) in APIs: 401 versus 403, credential types, roles and ownership checks, with working examples.
- Password Hashing and Login Store passwords safely: why hashing beats encryption, salts, slow hashes (scrypt, bcrypt, Argon2), constant-time comparison, login endpoints and password rules.
- HTTP Basic Auth and API Keys Understand HTTP Basic authentication (Authorization header, Base64, WWW-Authenticate) and API keys: generating, hashing, scoping, rotating and revoking them safely.
- Sessions and Cookies Learn how cookie-based sessions work: Set-Cookie attributes (HttpOnly, Secure, SameSite), session stores, login and logout, session fixation, CSRF and when sessions fit an API.
Tokens, JWT and OAuth
- JSON Web Tokens (JWT) Explained Learn what a JSON Web Token is, how header, payload and signature fit together, and build and verify an HS256 JWT by hand with node:crypto.
- JWT Pitfalls and Best Practices Avoid the classic JWT mistakes: alg none, algorithm confusion, long expiry and no revocation. Verify RS256 tokens with key pairs and a denylist in Node.js.
- Access Tokens and Refresh Tokens Learn why APIs pair short-lived access tokens with refresh tokens, how refresh token rotation and reuse detection work, with a runnable Node.js API.
- OAuth 2.0 Flows and PKCE Understand OAuth 2.0 roles, the authorization code flow with PKCE, client credentials and scopes, and run working simulators of each flow in Node.js.
- OpenID Connect: Logging In with OAuth Learn how OpenID Connect adds identity to OAuth 2.0: ID tokens, discovery, JWKS, nonce and userinfo, and validate an ID token step by step in Node.js.
- API Keys: Generate, Store and Rotate Design API keys properly: generate them with crypto randomness, store only a hash, look them up by prefix, scope, revoke and rotate them. Runnable Node.js demo.
API Security
- Authorization and Object-Level Access (BOLA) Learn the difference between authentication and authorization, why broken object-level authorization is the top API risk, and how to enforce ownership and roles.
- Input Validation and Mass Assignment Validate every API request: schemas, types and limits, safe error responses, allowlists against mass assignment, and parameterized queries against injection.
- Rate Limiting and Abuse Protection Protect your API from abuse and overload: fixed window, sliding window and token bucket algorithms, 429 responses, rate limit headers and login throttling.
- CORS and Security Headers Understand the same-origin policy, CORS preflight requests and credentials, then set the security headers and cookie flags every REST API should send.
Pagination, Caching and Versioning
- API Pagination: Offset, Page and Cursor Design API pagination that scales: offset and page numbers, cursor (keyset) pagination, Link headers, response envelopes, sorting rules and common pitfalls.
- HTTP Caching, ETags and Conditional Requests Speed up your API with HTTP caching: Cache-Control, ETag and If-None-Match for 304 responses, Last-Modified, Vary, and If-Match for safe concurrent updates.
- API Versioning and Evolution Change an API without breaking clients: breaking versus safe changes, URL, header and date versioning, the Deprecation and Sunset headers, and a migration plan.
Documentation and Testing
- Documenting APIs with OpenAPI Learn the OpenAPI Specification: paths, operations, schemas, parameters, responses and security schemes, and use a spec to generate docs and validate requests.
- Testing REST APIs Learn how to test a REST API: what to assert, test isolation, table-driven tests, authentication and error cases, plus a runnable test runner in Node.js.
- Contract Testing and Mock Servers Learn consumer-driven contract tests, provider verification, mock servers built from a spec, and fault injection so clients are ready for slow or failing APIs.
Projects and Practice
- Project: A Secure Notes API Build a complete notes API in Node.js: password hashing, short-lived JWTs, rotating refresh tokens, ownership checks, login throttling, pagination and ETags.
- Project: A Mini OAuth 2.0 Provider Build a miniature OAuth 2.0 authorization server with PKCE, RS256 access tokens, a JWKS endpoint and a resource API that enforces scopes, then attack it.
- Practice: Security Review of a Vulnerable API Attack a deliberately vulnerable API, then a hardened one: brute force, BOLA, mass assignment, SQL injection, data exposure and alg none. Includes a route audit exercise.
- REST API Security and Design Cheat Sheet A one-page REST API cheat sheet: status codes, headers, authentication choices, token rules, security checklist, pagination, caching and error format, with two demos.