Express
npm init
make sure you use module instead of commonjs "type": "module",
npm i express nodemon
insert start script in package.json "server": "nodemon app.js"
run with 'npm run server' stop with 'ctrl + c'
const express = require("express");
import express from "express";
const app = express();
app.use(express.json());
app.listen(3000, () => {
});
const books = [
{ id: 1, title: "Dune", author: "Herbert", year: 1965 },
{ id: 2, title: "1984", author: "Orwell", year: 1949 },
];
export default app;// at the bottom
// --- Basic endpoint ---app.get("/", (req, res) => {
res.json({ message: "success" });
});
// --- Path parameter ---app.get("/books/:id", (req, res) => {
const id = parseInt(req.params.id);
const book = books.find((b) => b.id === id);
if (!book) return res.status(404).json({ detail: "book not found" });
res.json(book);
});
// --- Query parameter (optional) ---app.get("/books", (req, res) => {
const id = req.query.id ? parseInt(req.query.id) : null;
if (id === null) return res.json(books);
res.json(books.find((b) => b.id === id));
});
// --- POST with a JSON body ---app.post("/books", (req, res) => {
const book = req.body;
books.push(book);
res.json(book);
});
// --- Middleware (must be injected manually per app / route) ---app.use((req, res, next) => {
console.log(req.method);
next();
});
app.listen(8000, () => console.log("listening on :8000"));
|
Fast API
if new `uv init[projectName]` then cd into it `code.`
`uv add fastapi`
`uv add uvicorn`
Auto-generated interactive docs are served at `/docs` once the app is running
# Run: uvicorn main:app --reload (serves on http://localhost:8000)
# stop the uvicorn server : ctrl + c
from fastapi import FastAPI, HTTPException
app = FastAPI()
# Using a local list instead of a database for the demo:
books = [
{"id": 1, "title": "Dune", "author": "Herbert", "year": 1965},
{"id": 2, "title": "1984", "author": "Orwell", "year": 1949},
]
# --- Basic endpoint (decorator = @app.(path)) ---test with http://localhost:8000/
@app.get("/")
def handler():
return {"message": "success"}
# --- Path parameter ---
# The magic of FastAPI: path params, query params, and JSON bodies ALL arrive
# as plain arguments to the handler. Just type-annotate them
# test with http://localhost:8000/books/2
@app.get("/books/{id}")
def get_book(id: int): # `id: int` -> FastAPI parses/validates it
for book in books:
if book["id"] == id:
return book
raise HTTPException(status_code=404, detail="book not found")
# --- Query parameter (optional -> give it a default of None) ---
test with http://localhost:8000/books?id=2
test with http://localhost:8000/books
@app.get("/books")
def list_books(id: int | None = None):
if id is None:
return books
return next((b for b in books if b["id"] == id), None)
# --- POST with a JSON body (type it and it's parsed for you) ---@app.post("/books")
def create_book(book: dict):
books.append(book)
return book
# --- Middleware: one decorator makes it universal (applies to ALL endpoints) ---@app.middleware("http")
async def log_requests(request, call_next):
print(request.method)
response = await call_next(request) # call_next is async -> always await it
return response
|