AlgoViz

API design introduction

easy 24 min

An API is a contract: it says what a program may ask for and what it gets back, and it hides how the work is done.

A tiny API without a framework

Read it, run it, change a line and run it again.

Loading editor…

It parses a request, checks it and routes it. A framework does the same with more care.

The same in Python
# FastAPIfrom typing import List, Optionalfrom fastapi import FastAPI, HTTPException, Queryfrom pydantic import BaseModelapp = FastAPI(title="ShopEasy API", version="1.0.0")class Product(BaseModel):    id: str    name: str    price: float    category: str    stock: intproducts_db = {    "PROD-001": Product(id="PROD-001", name="Wireless Headphones", price=149.99, category="electronics", stock=50),}@app.get("/products", response_model=List[Product])def list_products(    category: Optional[str] = Query(None),    min_price: Optional[float] = Query(None, ge=0),    max_price: Optional[float] = Query(None, ge=0),    limit: int = Query(20, ge=1, le=100),):    """Retrieve products with optional filters."""    result = list(products_db.values())    if category:        result = [p for p in result if p.category == category]    if min_price is not None:        result = [p for p in result if p.price >= min_price]    if max_price is not None:        result = [p for p in result if p.price <= max_price]    return result[:limit]@app.get("/products/{product_id}", response_model=Product)def get_product(product_id: str):    if product_id not in products_db:        raise HTTPException(status_code=404, detail="Product not found")    return products_db[product_id]
The same in JavaScript
// Expressconst express = require("express");const app = express();app.use(express.json());const products = new Map([  ["PROD-001", { id: "PROD-001", name: "Wireless Headphones", price: 149.99, category: "electronics", stock: 50 }],]);app.get("/products", (req, res) => {  const { category, min_price, max_price, limit = "20" } = req.query;  const n = Number(limit);  if (!Number.isInteger(n) || n < 1 || n > 100) {    return res.status(422).json({ error: "limit must be between 1 and 100" });  }  let result = [...products.values()];  if (category) result = result.filter((p) => p.category === category);  if (min_price !== undefined) result = result.filter((p) => p.price >= Number(min_price));  if (max_price !== undefined) result = result.filter((p) => p.price <= Number(max_price));  res.json(result.slice(0, n));});app.get("/products/:id", (req, res) => {  const product = products.get(req.params.id);  if (!product) return res.status(404).json({ error: "Product not found" });  res.json(product);});app.listen(3000, () => console.log("API running on port 3000"));
The same in Go
// Ginpackage mainimport (	"net/http"	"github.com/gin-gonic/gin")type Product struct {	ID       string  `json:"id"`	Name     string  `json:"name"`	Price    float64 `json:"price"`	Category string  `json:"category"`	Stock    int     `json:"stock"`}var products = map[string]Product{	"PROD-001": {ID: "PROD-001", Name: "Wireless Headphones", Price: 149.99, Category: "electronics", Stock: 50},}func main() {	r := gin.Default()	r.GET("/products", func(c *gin.Context) {		category := c.Query("category")		result := make([]Product, 0)		for _, p := range products { // map order is random: sort before you page			if category == "" || p.Category == category {				result = append(result, p)			}		}		c.JSON(http.StatusOK, result)	})	r.GET("/products/:id", func(c *gin.Context) {		if product, ok := products[c.Param("id")]; ok {			c.JSON(http.StatusOK, product)		} else {			c.JSON(http.StatusNotFound, gin.H{"error": "Product not found"})		}	})	r.Run(":8080")}