Skip to content
StackPractices

api

Practical resources about api for software engineers.

99 results

Building Robust APIs

APIs are the contract between systems. Whether you are exposing a public REST endpoint, designing an internal GraphQL schema, or integrating with a third-party service, the patterns you choose determine reliability, performance, and developer experience.

Here you will find recipes for handling CORS, implementing pagination, versioning endpoints, managing rate limits, and documenting APIs with OpenAPI. Each example includes runnable code in multiple languages so you can adapt it to your stack immediately.

intermediate

Stream LLM Output with Server-Sent Events (SSE)

Stream LLM responses to clients in real-time using Server-Sent Events with FastAPI, OpenAI streaming, and async generators for token-by-token output

beginner

Create API Documentation with OpenAPI

Generate interactive API docs from OpenAPI specs using Swagger UI, Redoc, and native tools in Python, JavaScript, and Java.

intermediate

Implement API Logging and Audit Trails

Set up thorough request/response logging and audit trails for APIs with structured output, correlation IDs, and compliance considerations.

intermediate

API Rate Limiting

Protect APIs from abuse and ensure fair resource usage with token bucket, sliding window, and leaky bucket rate limiting.

intermediate

Implement API Rate Limiting with Redis

Protect APIs from abuse using token bucket and sliding window algorithms with Redis, including burst handling, distributed coordination, and custom headers for client feedback

intermediate

API Versioning

How to version REST and GraphQL APIs to maintain backward compatibility while evolving your interface.

beginner

Call a REST API

How to make HTTP requests to a REST API and handle the JSON response in multiple languages.

intermediate

Cursor-Based Pagination with PostgreSQL

Implement efficient cursor-based pagination for large datasets in PostgreSQL, avoiding OFFSET performance degradation with indexed keyset pagination and stable sort ordering

intermediate

Express.js Middleware Composition Patterns

Build maintainable Express applications using middleware composition patterns for authentication, validation, error handling, request context propagation, and async route wrappers

intermediate

Go REST API with Gin and Middleware

Build production-ready REST APIs in Go using the Gin framework with custom middleware for logging, authentication, validation, and error handling

intermediate

Implement a GraphQL API

Build a production-ready GraphQL API with type-safe schemas, resolvers, and query optimization in Python, JavaScript, and Java.

intermediate

Build a GraphQL API with Apollo Server and TypeScript

How to build a production-ready GraphQL API using Apollo Server, TypeScript, and DataLoader to solve the N+1 query problem

intermediate

Implement a gRPC API with Protocol Buffers

How to implement a gRPC API using Protocol Buffers for high-performance service-to-service communication

intermediate

gRPC Services with Protocol Buffers in TypeScript

Build high-performance, strongly-typed services using gRPC with Protocol Buffers, covering unary calls, server streaming, client streaming, and bidirectional streaming

intermediate

Handle CORS Correctly

How to configure Cross-Origin Resource Sharing (CORS) headers correctly for APIs, SPAs, and serverless functions without opening security holes.

intermediate

Handle Errors in APIs

Patterns for consistent, predictable API error handling across multiple languages and frameworks.

intermediate

Idempotent API Endpoints

How to design and implement idempotent API endpoints that safely handle retries, duplicate requests, and network failures without side effects.

beginner

Input Validation

How to validate user input safely using schemas, type checking, and sanitization across Python, JavaScript, and Java.

intermediate

JavaScript Fetch Retry Logic with Exponential Backoff

Retry failed HTTP requests in JavaScript with exponential backoff

beginner

Logging

How to implement structured, level-based logging across Python, JavaScript, and Java with what works for production observability.

intermediate

Middleware

How to implement request/response middleware for logging, auth, and error handling across Python, JavaScript, and Java.

intermediate

Configure Nginx as a Reverse Proxy and API Gateway

How to use Nginx as a reverse proxy for backend services, implement load balancing, SSL termination, and rate limiting for production API gateways

intermediate

Node.js WebSocket Real-Time Communication with Socket.io

Build real-time WebSocket applications in Node.js with Socket.io

intermediate

Pagination

How to implement cursor-based and offset-based pagination in APIs and databases across Python, JavaScript, and SQL.

intermediate

Python API Rate Limiting with Token Bucket

Implement token bucket rate limiting in Flask and FastAPI with Redis support

intermediate

Rate Limiting

How to implement API rate limiting using token bucket, sliding window, and fixed window algorithms across Python, JavaScript, and Java.

intermediate

Build Real-Time Notifications with WebSockets

Implement a real-time notification system using WebSockets and Redis pub/sub for broadcasting messages across clients.

intermediate

REST API Design: What Works

Design reliable, scalable REST APIs with proper HTTP methods, status codes, versioning, and pagination strategies.

intermediate

Send Emails with SMTP

How to send transactional and bulk emails securely using SMTP with template support.

intermediate

Server-Sent Events (SSE)

How to implement one-way real-time streaming from server to browser using Server-Sent Events, with reconnection, event types, and multi-client broadcasting.

intermediate

Implement Server-Sent Events in Go for Real-Time Updates

How to build a production-ready Server-Sent Events endpoint in Go with connection management, heartbeat pings, and graceful client disconnect handling

intermediate

Server-Sent Events with Node.js and Express

Implement real-time server-to-client push using Server-Sent Events in Node.js with Express, covering connection management, event types, reconnection logic, and backpressure handling

intermediate

Webhooks

How to create and consume webhook endpoints for real-time event-driven integrations.

intermediate

WebSocket Authentication and Security Patterns

How to authenticate WebSocket connections, implement token validation, and handle authorization for real-time messaging in production

intermediate

Build a Bidirectional Chat with WebSocket and Node.js

How to build a real-time bidirectional chat application using WebSocket with room-based messaging, presence tracking, and message persistence

intermediate

WebSocket Server

How to build a WebSocket server for bidirectional real-time communication, with connection management, message broadcasting, and heartbeat keepalive.

intermediate

Use Spring Cache Annotations with Redis Backend

Apply Spring's @Cacheable, @CachePut, and @CacheEvict annotations with a Redis cache manager for declarative caching in Java applications.

intermediate

Implement Redis Cache Invalidation in Node.js

Invalidate Redis cache entries in Node.js with TTL expiry, explicit deletion, pattern-based clearing, and pub/sub-based distributed invalidation.

intermediate

Cache HTTP Responses with httpx and CacheControl in Python

Cache HTTP responses in Python using httpx with CacheControl for HTTP-compliant caching, ETag handling, and conditional requests.

intermediate

Store User Sessions in Memcached with Python

Use Memcached as a distributed session store in Python web applications with pymemcache, TTL management, and failover handling.

advanced

Compose Asynchronous Pipelines with Java CompletableFuture

Build non-blocking async pipelines in Java using CompletableFuture with thenCompose, thenCombine, allOf, anyOf, exception handling, timeouts, and custom thread pools.

intermediate

Make Concurrent HTTP Requests with Python and aiohttp

Fetch multiple APIs concurrently using asyncio and aiohttp. Covers connection pooling, rate limiting, retries, and batch processing.

intermediate

Concurrent Async Tasks with asyncio.gather and Task Groups

Execute multiple async operations concurrently in Python using asyncio.gather, asyncio.TaskGroup, error handling with return_exceptions, timeouts, and semaphores for rate limiting.

intermediate

Rate Limit Async Operations with asyncio.Semaphore

Control concurrency in async Python using asyncio.Semaphore for rate limiting API calls, database connections, and resource access with bounded parallelism patterns.

intermediate

Extract Data from HTML Pages with Python and BeautifulSoup

Parse HTML and extract data using BeautifulSoup. Covers CSS selectors, navigation, tables, pagination, and respectful scraping with rate limiting.

intermediate

Custom GraphQL Scalar Types for Dates, Emails, and JSON

Define custom GraphQL scalars for Date, Email, URL, and JSON fields with serialization, parsing, and validation logic

intermediate

Batch and Cache Database Queries with GraphQL DataLoader

Use DataLoader to coalesce individual load requests into batched database calls, solving the N+1 query problem in GraphQL resolvers

advanced

Field-Level Auth with Custom GraphQL Schema Directives

Implement field-level authorization in GraphQL using custom schema directives that check user roles and permissions per field

intermediate

Structured GraphQL Errors with Extension Codes

Implement structured error handling in GraphQL with custom error classes, extension codes, and consistent error formatting for clients

advanced

Set Up a GraphQL Federation Gateway with Apollo

Compose multiple GraphQL services into a single federated supergraph using Apollo Federation and a gateway that routes queries across subgraphs

intermediate

Validate and Sanitize GraphQL Input Types Server-Side

Implement centralized input validation in GraphQL using custom validation functions, Zod schemas, and input type transforms

beginner

Mock GraphQL Resolvers for Frontend Development

Set up mocked GraphQL resolvers with Apollo Server so frontend teams can develop against a fake API before the backend is ready

intermediate

Detect and Fix N+1 Queries in GraphQL Resolvers

Identify N+1 query problems in GraphQL resolvers using logging, DataLoader, and query analysis tools before they hit production

intermediate

Cursor-based Pagination with GraphQL Relay Connections

Implement Relay-style cursor pagination in GraphQL with edges, nodes, and pageInfo for efficient forward and backward traversal

advanced

Real-Time Data with GraphQL WebSocket Subscriptions

Implement GraphQL subscriptions over WebSockets with Apollo Server and PubSub for real-time updates pushed to connected clients

beginner

Schema-Based Data Validation with Zod in TypeScript

Validate and sanitize incoming data using Zod schemas with TypeScript inference, custom refinements, and error formatting for reliable API and form validation

intermediate

Configure HTTP Security Headers with Helmet in Node.js

Set security HTTP headers in Express apps with Helmet — CSP, HSTS, X-Frame-Options, X-Content-Type-Options, and CORS for OWASP-compliant web security

intermediate

Build HTTP-Triggered Azure Functions with Python

Create HTTP-triggered Azure Functions in Python with binding configuration, async handlers, dependency injection, and deployment via Azure CLI.

intermediate

Deploy HTTP Cloud Functions on Google Cloud with Node.js

Create and deploy HTTP-triggered Cloud Functions on Google Cloud with Node.js, Express integration, secrets management, and gcloud CLI deployment.

advanced

Secure API Gateway with Custom Lambda Authorizers

Implement custom Lambda authorizers for API Gateway with JWT validation, IAM policy generation, and caching for token-based authentication in serverless APIs.

intermediate

Backends for Frontends: Dedicated Backend per Client Type

How to create dedicated backends per client type. Covers BFF for web, mobile, and desktop. Covers API aggregation, client-specific optimization, and GraphQL BFF.

intermediate

Gateway Routing Pattern

Route requests to multiple backend services through a single entry point that handles cross-cutting concerns.

beginner

Adapter Pattern for Integrating External REST APIs

Use the Adapter pattern to normalize responses from external REST APIs into a consistent internal model without leaking third-party formats into your domain

intermediate

Backend for Frontend (BFF) Pattern

Create dedicated backend services tailored to the specific needs of each frontend client type, aggregating downstream APIs and optimizing data shapes per platform.

intermediate

Chain of Responsibility for Request Processing Middleware

Pass requests along a chain of handlers where each handler decides whether to process the request or pass it to the next handler in the pipeline

intermediate

Decorator Pattern for HTTP Request Pipelines

Use the Decorator pattern to compose cross-cutting concerns like logging, metrics, and retries into HTTP request pipelines without modifying core logic

intermediate

GraphQL Batched Resolver Pattern

Resolve nested GraphQL fields in a single batched request to eliminate N+1 queries and reduce database load.

intermediate

GraphQL DataLoader Pattern

Coalesce individual load requests into batched calls with per-request caching to prevent N+1 queries and redundant fetches.

intermediate

GraphQL Error Extension Pattern

Attach structured metadata to GraphQL errors using extension codes for predictable client-side error handling.

advanced

GraphQL Interface Polymorphism Pattern

Model polymorphic types with GraphQL interfaces to share field contracts across different object types while keeping resolvers type-specific.

advanced

GraphQL Schema Stitching Pattern

Merge multiple independent GraphQL schemas into a single unified schema that clients can query as one graph.

intermediate

Token Bucket Rate Limiter: Smooth Traffic with Token Buckets

How to implement token bucket rate limiting for API protection. Covers bucket refill, burst handling, per-key buckets, distributed rate limiting with Redis, and sliding windows.

beginner

API Changelog Template

A template for documenting API changes including breaking changes, new features, deprecations, and bug fixes.

beginner

API Deprecation Notice Template

A template for communicating API deprecations, breaking changes, and sunset timelines to consumers.

beginner

API Error Handling Guideline

A guideline for standardizing error responses, status codes, and error payloads across REST and GraphQL APIs.

intermediate

API Rate Limiting Policy Template

A template for defining API rate limits per consumer tier, including burst allowances, quota periods, and escalation paths.

intermediate

SLA Definition Template

A template for defining and documenting Service Level Agreements including uptime targets, response times, error budgets, and escalation procedures.

beginner

API Documentation Template

A reusable template for documenting REST and GraphQL APIs with endpoints, schemas, errors, and examples.

intermediate

API Error Response Template

A reusable template for consistent, informative, and developer-friendly API error responses that reduce debugging time.

beginner

API Status Page Template

A template for a public API status page that communicates uptime, incidents, and maintenance windows to consumers.

advanced

Complete Guide to OpenAI API Mastery

Master the OpenAI API in production. Covers chat completions, streaming, function calling, structured outputs, embeddings, fine-tuning, batch API, assistants API, rate limits, error handling, and cost optimization patterns.

intermediate

Complete Guide to API Versioning Strategies

Version REST and GraphQL APIs with URI, header, query param, and content negotiation strategies. Covers deprecation, sunset, and migration patterns.

advanced

Complete Guide to GraphQL Federation

Build unified GraphQL APIs across multiple services with Apollo Federation. Covers subgraphs, supergraph composition, entity resolution, and gateway deployment.

advanced

GraphQL Federation in Production

Run federated GraphQL in production with confidence. Covers subgraph composition, gateway deployment, entity resolution, schema coordination, observability, and failure handling.

advanced

Complete Guide to GraphQL Schema Design

Design GraphQL schemas for evolution, performance, and maintainability. Covers type design, connections, mutations, error handling, deprecation, and schema-first vs code-first workflows.

advanced

Complete Guide to GraphQL Security

Secure GraphQL APIs against introspection leaks, query depth attacks, cost-based DoS, batching abuse, and injection. Covers auth patterns, rate limiting, and production hardening.

advanced

Complete Guide to GraphQL Testing

Test GraphQL APIs at every layer: unit tests for resolvers, integration tests for schema, E2E tests for operations. Covers mocking, fixtures, snapshot testing, and performance testing.

intermediate

REST API Design Guide

A thorough guide to designing clean, scalable, and maintainable REST APIs.

advanced

API Gateway Design: Resilience, Routing, and Security

A practical guide to designing API gateways: routing patterns, rate limiting, authentication, circuit breakers, and observability for resilient APIs.

intermediate

Complete Guide to Microservices Communication

Compare sync vs async communication patterns for microservices. Covers REST, gRPC, message queues, event-driven, service mesh, and when to use each.

intermediate

GraphQL vs REST — When to Choose and How to Migrate

A decision guide comparing GraphQL and REST APIs: use cases, performance, caching, tooling, and migration strategies for engineering teams.

advanced

gRPC in Microservices — High-Performance RPC Guide

A practical guide to gRPC for microservices: Protocol Buffers, streaming, load balancing, and migration from REST for high-performance RPC.

intermediate

API Rate Limiting — Design Fair and Useful Throttling

A practical guide to API rate limiting: token bucket, leaky bucket, sliding window algorithms, choosing limits, and implementing resilient throttling for APIs.

intermediate

API Security Checklist — Authentication to Encryption

A thorough security checklist for APIs: authentication, authorization, input validation, rate limiting, encryption, logging, and deployment hardening.

advanced

Complete Guide to API Security

Secure your APIs end-to-end. Covers rate limiting, authentication, input validation, CORS, SQL injection prevention, API gateway patterns, request size limits, pagination security, mass assignment, versioning, audit logging, and API security testing with practical code examples.

advanced

Complete Guide to Authentication Patterns

Implement authentication in production. Covers JWT, OAuth2, session-based auth, passkeys, MFA, refresh tokens, token rotation, RBAC, ABAC, SSO with SAML and OpenID Connect, and secure logout patterns with practical code examples.

advanced

Complete Guide to OWASP Top 10 2025

Mitigate each OWASP Top 10 2025 risk with practical code examples. Covers broken access control, cryptographic failures, injection, insecure design, security misconfiguration, vulnerable components, auth failures, software integrity, logging failures, and SSRF.

intermediate

Web Application Security (OWASP Top 10)

A developer-focused guide to the OWASP Top 10: injection, broken access control, XSS, insecure design, and how to prevent each vulnerability with code examples.

intermediate

Webhook Security — Delivery, Verification, and Protection

A practical guide to securing webhooks: signature verification, replay attack prevention, payload encryption, and endpoint hardening for reliable delivery.