CodeNFacts
CodeHub
Home

All Categories


Sign In
connection established

API . Field Guide

Everything about Application Programming Interfaces - what they are, why they exist, every major type, the formulas behind rate limits and uptime, diagrams of how requests actually travel, cheat sheets, and a walkthrough of wiring your own AI model up as an API.

free · no signup · ~1 min read summary
200 OK · 84ms
GET /api/v1/whatIsAnApi
{
  "answer": "a contract two programs use to talk",
  "returns": "predictable, structured data"
}
GET/overview

What is an API — and why does it exist?

The one-sentence version, then the reasons it became the backbone of modern software.

Definition

An API (Application Programming Interface) is a defined set of rules — endpoints, request formats, and response formats — that lets one piece of software ask another piece of software to do something or hand over data, without either side needing to know how the other is built internally.

A simple analogy

Think of a restaurant menu. You (the client) don't walk into the kitchen and cook — you order from the menu (the API), the kitchen (the server) prepares it however it wants internally, and a waiter (the network) brings back exactly what you ordered.

Abstraction — hides internal complexity behind a simple, stable contract.

Reusability — one backend can power web, mobile, and third-party apps at once.

Interoperability — lets systems written in different languages talk to each other.

Why it's needed (not just useful)

  • • Frontend and backend teams can build in parallel against a contract.
  • • One backend safely powers web, iOS, Android and partners at once.
  • • You can swap the internal implementation without breaking callers.
  • • Third parties can build on top of your product without touching your code.
GET/types

Types of APIs

Six shapes of API you'll run into in the wild — and when each one wins.

GETGET /types/rest

REST

Resource-oriented architecture over HTTP. Uses standard verbs (GET, POST, PUT, DELETE) and URLs to represent resources.

Simple & widely understoodCacheable via HTTPStateless, scales horizontally
Over/under-fetching dataMultiple round trips for nested data
GET /api/users/42
GETGET /types/graphql

GraphQL

A query language where the client specifies exactly the shape of data it needs, in a single request to one endpoint.

No over/under-fetchingSingle endpointStrongly typed schema
Caching is harderQuery complexity can hurt performance
POST /graphql  { user(id: 42) { name email } }
GETGET /types/soap

SOAP

A strict, XML-based protocol with built-in standards for security (WS-Security) and transactions. Common in banking/enterprise.

Strong typing via WSDLBuilt-in error handlingEnterprise-grade security
Verbose XML payloadsSlower & harder to work with
<soap:Envelope>...<GetUser/>...</soap:Envelope>
GETGET /types/grpc

gRPC

A high-performance RPC framework from Google using Protocol Buffers and HTTP/2 for fast, binary, streaming communication.

Very fast (binary + HTTP/2)Bi-directional streamingAuto-generated client code
Not human-readableLimited browser support
rpc GetUser(UserRequest) returns (UserResponse);
GETGET /types/websocket

WebSocket

A persistent, full-duplex connection between client and server — ideal for real-time, bidirectional communication.

Real-time, low latencyServer can push data anytime
Connection must stay openHarder to scale/load-balance
ws://api.example.com/live-chat
GETGET /types/webhook

Webhook

A 'reverse API' — instead of you polling a server, the server calls a URL you registered when an event happens.

No polling neededEfficient, event-driven
You must expose a public endpointDelivery/retry logic needed
POST https://yourapp.com/webhooks/payment-success
GET/architecture

Block Diagram — how a request actually travels

Client → Gateway (auth + rate limit) → Services → Database, end to end.

Client AppHTTPSAPI Gatewayauth · rate-limitroutingService AService BService CDatabase

Request / Response cycle

ClientServerRequest: GET /users/42 (headers, body)Response: 200 OK (headers, JSON body)
GET/formulas

Formulas every API engineer should know

The math behind rate limiting, throughput, uptime, retries and pagination.

Token Bucket Rate Limiting

tokens(t) = min( capacity, tokens(t−Δt) + r · Δt )

A bucket refills at rate r tokens/second up to a max capacity. Each request consumes 1 token; if the bucket is empty, the request is throttled (HTTP 429).

Little's Law (Throughput)

L = λ × W

Average number of in-flight requests (L) equals arrival rate (λ, req/sec) times average time each request spends in the system (W, sec). Used to size server capacity.

API Availability (Uptime)

Availability % = ((Total time − Downtime) / Total time) × 100

The classic SLA number. 99.9% ('three nines') allows ~8.7 hours of downtime a year; 99.99% allows ~52 minutes.

Exponential Backoff with Jitter

wait = min( cap, base × 2^attempt ) + random(0, jitter)

Used by clients retrying failed requests. Delay doubles each retry up to a cap, and random jitter is added so many clients don't retry in lockstep (the 'thundering herd').

Pagination Offset

offset = (page − 1) × limit

Converts a page number + page size into the SQL/API offset used to fetch the correct slice of records.

Success / Error Rate

Success Rate % = (Successful Requests ÷ Total Requests) × 100

Core health metric for any API — tracked per endpoint to catch regressions (commonly paired with p95/p99 latency).

Latency Percentile (p95)

p95 = value below which 95% of response times fall

Better than average latency because it reflects the experience of your slowest real users, not just the typical case.

GET/notes

Detailed notes

Expand each topic — methods, status codes, auth, REST constraints, idempotency, versioning, CORS, webhooks.

  • GET — retrieve a resource, safe & idempotent, no body.
  • POST — create a resource or trigger an action, not idempotent.
  • PUT — replace a resource entirely, idempotent.
  • PATCH — partially update a resource, not guaranteed idempotent.
  • DELETE — remove a resource, idempotent.
  • HEAD — like GET but returns headers only, used for existence/metadata checks.
  • OPTIONS — asks the server which methods/headers are allowed (used heavily in CORS preflight).
GET/diagrams

More diagrams & sketches

A quick sketch of the OAuth2 authorization-code flow used behind most 'log in with...' buttons.

1. User clicks 'Log in with X'
2. App redirects to Auth Server
3. User approves access
4. Auth Server returns code
5. App exchanges code for token
6. App calls API with token
GET/cheatsheet

Cheat sheets

Print these three tables and you're covered for 90% of API work.

MethodPurposeIdempotentCacheableBody
GETReadYesYesNo body
POSTCreate / actionNoNoHas body
PUTReplaceYesNoHas body
PATCHPartial updateUsually notNoHas body
DELETERemoveYesNoOptional body

Status codes

  • 200OK — request succeeded
  • 201Created — new resource made
  • 204No Content — success, empty body
  • 400Bad Request — malformed input
  • 401Unauthorized — missing/invalid auth
  • 403Forbidden — authenticated but not allowed
  • 404Not Found — resource doesn't exist
  • 409Conflict — state conflict (e.g. duplicate)
  • 422Unprocessable Entity — validation failed
  • 429Too Many Requests — rate limited
  • 500Internal Server Error
  • 503Service Unavailable — server overloaded/down

Common headers

  • AuthorizationCredentials: Bearer <token>, Basic <base64>
  • Content-TypeFormat of the request body, e.g. application/json
  • AcceptFormat the client wants back
  • X-API-KeyCommon custom header for API-key auth
  • Idempotency-KeyUnique id to make a retried POST safe
  • ETag / If-None-MatchCaching & conditional requests
  • Retry-AfterServer tells client how long to wait before retrying
POST/build-ai-model

How to build & serve your own AI model as an API

From raw idea to a POST /predict endpoint the rest of the world can call.

  1. 1

    Define the problem & data

    Pick a narrow task (classify text, forecast a number, generate an image) and gather/clean a labeled dataset.

  2. 2

    Choose a framework

    PyTorch or TensorFlow for training from scratch; or fine-tune/prompt an existing foundation model via its API (OpenAI, Anthropic, HuggingFace) to skip training entirely.

  3. 3

    Train / fine-tune the model

    Split data into train/validation/test sets, train, and evaluate with the right metric (accuracy, F1, RMSE) — iterate until it's good enough to ship.

  4. 4

    Export & serve the model

    Save weights (ONNX, SavedModel, .pt) and load them in a lightweight Python web server such as FastAPI or Flask.

  5. 5

    Wrap it in an API

    Expose an endpoint like POST /predict that accepts input JSON, runs model.predict(), and returns a JSON response — this is the contract the outside world uses.

  6. 6

    Add auth, validation & rate limiting

    Protect the endpoint with an API key or OAuth, validate incoming payloads (e.g. Pydantic), and apply the token-bucket formula above so one caller can't exhaust your GPU.

  7. 7

    Containerize & deploy

    Package with Docker, deploy to a host (AWS, GCP, Render, Fly.io) behind HTTPS, and put it behind a gateway/load balancer for scale.

  8. 8

    Monitor & iterate

    Log latency, error rate, and input drift. Retrain or fine-tune as real-world data comes in — the API layer is what lets other apps consume your model without ever seeing its internals.

GET/blog

The bigger picture — use cases, features, future & trade-offs

Where APIs show up in everyday products, and an honest look at both sides.

Use cases

  • Payments — Stripe/PayPal APIs move money without you handling card data directly.
  • Maps & location — Google Maps API renders maps and computes routes inside third-party apps.
  • AI & ML — OpenAI, Anthropic, and HuggingFace APIs let any app add language or vision intelligence.
  • Social login — 'Sign in with Google/GitHub' is OAuth2 APIs delegating identity.
  • IoT — smart devices report sensor data and accept commands through lightweight APIs.
  • Weather, finance & data feeds — real-time stock, currency, and weather data via public APIs.

Where APIs are headed

  • AI-native APIs — LLMs are increasingly consumed as APIs themselves, and are also starting to call other APIs autonomously ('tool use' / agents).
  • GraphQL & typed schemas growing for complex, data-heavy frontends.
  • Event-driven & streaming APIs (gRPC streams, WebSockets, Kafka-backed APIs) for real-time products.
  • API-as-a-product — companies increasingly monetize APIs directly (usage-based billing, marketplaces).
  • Stronger standardization around API security (zero-trust, mTLS, fine-grained OAuth scopes).

Good side

  • Faster development — reuse existing services instead of building from scratch.
  • Enables integration between completely different systems/platforms.
  • Encourages modular, maintainable architecture (microservices).
  • Opens new business models — API-first companies, developer ecosystems.

Bad side

  • Adds a dependency — if the API goes down or changes, your app breaks.
  • Security surface — every exposed endpoint is a potential attack vector.
  • Costs — many APIs are metered/paid, and usage can scale expensively.
  • Versioning & breaking changes require ongoing maintenance discipline.

Take these notes with you

Every section on this page — definitions, formulas, cheat sheets and the AI-model build steps — bundled into one Markdown file.

built like a schematic · GET /overview → POST /build-ai-model