惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Engineering at Meta
Engineering at Meta
人人都是产品经理
人人都是产品经理
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
量子位
腾讯CDC
The Cloudflare Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
云风的 BLOG
云风的 BLOG
Vercel News
Vercel News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
L
LangChain Blog
aimingoo的专栏
aimingoo的专栏
The Hacker News
The Hacker News
T
The Exploit Database - CXSecurity.com
B
Blog
S
SegmentFault 最新的问题
P
Privacy & Cybersecurity Law Blog
T
Threatpost
博客园 - 聂微东
T
Tailwind CSS Blog
The Last Watchdog
The Last Watchdog
C
Check Point Blog
N
Netflix TechBlog - Medium
D
DataBreaches.Net
爱范儿
爱范儿
IT之家
IT之家
S
Secure Thoughts
M
MIT News - Artificial intelligence
NISL@THU
NISL@THU
C
Cisco Blogs
TaoSecurity Blog
TaoSecurity Blog
有赞技术团队
有赞技术团队
A
Arctic Wolf
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
P
Proofpoint News Feed
Spread Privacy
Spread Privacy
Schneier on Security
Schneier on Security
Simon Willison's Weblog
Simon Willison's Weblog
G
GRAHAM CLULEY
雷峰网
雷峰网
Project Zero
Project Zero
博客园 - Franky
H
Heimdal Security Blog
A
About on SuperTechFans
Security Latest
Security Latest
Webroot Blog
Webroot Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Hugging Face - Blog
Hugging Face - Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Best Python Libraries for Building REST APIs Without a Full Framework in 2026
Kyle Rhodelander · 2026-06-18 · via DEV Community

Best Python Libraries for Building REST APIs Without a Full Framework in 2026

If you've spent any time building Python web services, you know the feeling: you open a new project, reach for Django or Flask, and then stop yourself. Do I really need all of this? Sometimes you don't. Sometimes you want to own your stack, pick your own pieces, and avoid dragging in hundreds of lines of framework boilerplate for an API that serves twenty endpoints.

The good news is that the Python ecosystem in 2026 is absolutely stacked with purpose-built libraries that handle specific parts of the REST API puzzle — routing, serialization, validation, authentication, documentation — without forcing you into a monolithic framework. You compose the stack yourself, and the result is leaner, faster, and easier to reason about.

This post breaks down the best libraries in each category, when to use them, and how they fit together.


Why Go Frameworkless?

Before diving in, let's be clear about the trade-off. Full frameworks like FastAPI, Django REST Framework, or Flask-RESTful are excellent and genuinely worth using for most projects. But there are real scenarios where rolling your own stack pays off:

  • Microservices with narrow responsibilities — a single service that does one thing doesn't need an ORM, a templating engine, or admin scaffolding.
  • Performance-critical APIs — fewer layers mean fewer allocations and faster response times.
  • Learning and ownership — understanding what each layer does makes you a better engineer.
  • Custom requirements — sometimes framework opinions conflict with your architecture decisions.

With that context, here's what you actually need to build a production REST API:

  1. An ASGI/WSGI server
  2. A router
  3. Request/response handling
  4. Validation and serialization
  5. Authentication middleware
  6. Documentation generation
  7. Testing utilities

Let's tackle each one.


ASGI Servers: The Foundation

Uvicorn

Uvicorn is the de-facto ASGI server for Python in 2026. Built on uvloop and httptools, it's blazing fast and handles HTTP/1.1, HTTP/2, and WebSockets. It's what FastAPI and Starlette run on under the hood.

pip install uvicorn[standard]

You can run any ASGI application with it:

# main.py
async def app(scope, receive, send):
    assert scope['type'] == 'http'
    await send({'type': 'http.response.start', 'status': 200, 'headers': []})
    await send({'type': 'http.response.body', 'body': b'Hello, world'})

uvicorn main:app --reload

For production, pair it with Gunicorn using the Uvicorn worker class for process management.

Granian

If you're chasing raw performance in 2026, Granian is worth a look. It's a Rust-based HTTP server with native ASGI support that consistently benchmarks faster than Uvicorn in high-throughput scenarios. Drop-in replacement in most cases.


Routing: Starlette's Router as a Standalone Component

Starlette Router

Here's something most people don't realize: you can use Starlette's Router class completely independently without adopting the full Starlette application. It gives you clean URL routing, path parameters, and middleware support.

from starlette.routing import Router, Route
from starlette.requests import Request
from starlette.responses import JSONResponse

async def get_users(request: Request):
    return JSONResponse({"users": []})

async def get_user(request: Request):
    user_id = request.path_params["user_id"]
    return JSONResponse({"id": user_id})

routes = [
    Route("/users", get_users),
    Route("/users/{user_id:int}", get_user),
]

app = Router(routes=routes)

This gives you exactly what you need without pulling in Starlette's middleware stack, background tasks, or static file handling unless you want them.

RSGI Router (Alternative: lilya)

Lilya is an evolution of Esmerald's internals that works as a standalone ASGI router. It's more opinionated than raw Starlette routing but still much lighter than a full framework. Worth checking out if you want slightly more structure around path operations.


Validation and Serialization

This is where most of the heavy lifting happens in any API, and this is the category where Python has the richest selection.

Pydantic v2

Pydantic is the gold standard for data validation in Python. Version 2 rewrote the core in Rust, making it dramatically faster than v1. Even without FastAPI wrapping it, you can use Pydantic directly to validate incoming request bodies and serialize outgoing responses.

from pydantic import BaseModel, EmailStr, field_validator

class CreateUserRequest(BaseModel):
    name: str
    email: EmailStr
    age: int

    @field_validator('age')
    @classmethod
    def age_must_be_positive(cls, v):
        if v < 0:
            raise ValueError('Age must be non-negative')
        return v

# In your route handler
async def create_user(request: Request):
    body = await request.json()
    try:
        user_data = CreateUserRequest(**body)
    except ValidationError as e:
        return JSONResponse(e.errors(), status_code=422)
    # ... persist user_data

Pydantic's model_dump() for serialization and .model_validate() for validation cover 95% of your needs cleanly.

Marshmallow

Marshmallow is the older sibling — it predates Pydantic and takes a different philosophy. Schema definitions are separate from your data models, which some teams prefer for explicit separation of concerns. It's also more flexible for complex nested serialization scenarios.

pip install marshmallow

Marshmallow is a particularly good choice if you're working with SQLAlchemy models and don't want to duplicate your schema definitions as Pydantic models.

Msgspec

For pure performance obsessives, msgspec is extraordinary. It's a Rust-backed library that handles both validation and serialization, and it's measurably faster than Pydantic v2 in many benchmarks. The API is slightly less ergonomic, but for high-throughput APIs the performance gains are real.


HTTP Client-Side: Handling Requests Properly

httpx

When your API needs to call other services (and they all do eventually), httpx is the right tool. It's fully async, supports HTTP/2, and has a nearly identical interface to requests so the learning curve is minimal.

pip install httpx

It also has a test client that lets you make requests against your ASGI app without spinning up a real server — which becomes important in the testing section.


Authentication and Authorization

PyJWT

PyJWT handles JWT encoding and decoding without opinionated middleware built around a specific framework. You write your own middleware, but that's exactly the point — you control the flow.

import jwt
from starlette.middleware.base import BaseHTTPMiddleware

SECRET_KEY = "your-secret"
ALGORITHM = "HS256"

class JWTMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        token = request.headers.get("Authorization", "").replace("Bearer ", "")
        try:
            payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
            request.state.user = payload
        except jwt.ExpiredSignatureError:
            return JSONResponse({"error": "Token expired"}, status_code=401)
        except jwt.InvalidTokenError:
            return JSONResponse({"error": "Invalid token"}, status_code=401)
        return await call_next(request)

Authlib

For OAuth 2.0 flows, Authlib is the most complete Python implementation. It handles token issuance, refresh flows, and integrates with popular identity providers. Unlike framework-specific OAuth libraries, Authlib works with any ASGI stack.


Rate Limiting and Caching

slowapi

slowapi is inspired by Flask-Limiter and works independently with any ASGI application. It uses Redis or in-memory backends for tracking request counts.

aiocache

aiocache gives you async caching with Redis, Memcached, or in-memory backends. Caching serialized responses is often the single highest-impact optimization you can make to an API.


Database Access Without an ORM

If you're frameworkless, you probably don't want a heavy ORM either. Two libraries stand out:

SQLAlchemy Core (not ORM)

SQLAlchemy is famous for its ORM, but the Core layer gives you a powerful SQL expression language and connection pooling without any ORM magic. Pair it with the async extension and you have a solid database layer.

from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy import text

engine = create_async_engine("postgresql+asyncpg://user:pass@localhost/db")

async def get_users():
    async with AsyncSession(engine) as session:
        result = await session.execute(text("SELECT * FROM users"))
        return result.fetchall()

Databases

The databases library from the Encode team (same people who built Starlette) provides a simple async interface to PostgreSQL, MySQL, and SQLite without the SQLAlchemy overhead. It's the lightest path to async database queries.


API Documentation

One thing you lose going frameworkless is automatic OpenAPI documentation. Here's how to get it back.

spectree

spectree generates OpenAPI specs from your Pydantic models and route decorators. It works with Starlette, Flask, and raw ASGI applications. Add it to your router and it generates /docs and /redoc endpoints automatically.

Manual OpenAPI with PyYAML

For smaller APIs, maintaining an openapi.yaml by hand and serving it at /docs via Swagger UI (loaded from a CDN) is a perfectly valid approach. Less magic, full control.


Testing Your Frameworkless API

pytest + httpx

The combination of pytest and httpx's AsyncClient is the cleanest way to test ASGI applications:

import pytest
from httpx import AsyncClient, ASGITransport
from main import app

@pytest.mark.asyncio
async def test_get_users():
    async with AsyncClient(
        transport=ASGITransport(app=app), base_url="http://test"
    ) as client:
        response = await client.get("/users")
    assert response.status_code == 200
    assert "users" in response.json()

No running server required, full request/response lifecycle tested.

pytest-asyncio

Don't forget pytest-asyncio for marking async test functions. Set asyncio_mode = "auto" in your pytest.ini to avoid decorating every test.


Putting It All Together: A Minimal Stack

Here's a practical stack recommendation for a production-ready frameworkless REST API in 2026:

Layer Library Why
Server Uvicorn + Gunicorn Proven, production-ready
Routing Starlette Router Lightweight, clean API
Validation Pydantic v2 Best-in-class DX + Rust speed
Database SQLAlchemy Core async Flexible, battle-tested
Auth PyJWT + Authlib Composable, not opinionated
Caching aiocache + Redis Async-native
Docs spectree OpenAPI without the framework
Testing pytest + httpx Fast, no server required

Install the essentials:

pip install uvicorn[standard] starlette pydantic[email] \
    sqlalchemy[asyncio] asyncpg pyjwt authlib \
    aiocache spectree pytest pytest-asyncio httpx

This stack gives you everything a FastAPI project would give you, but you understand exactly what every dependency does. When something breaks, you know where to look.


Honest Caveats

Going frameworkless isn't free. You'll spend more time wiring things together upfront. You'll write your own middleware for things FastAPI handles automatically. If your team has junior developers, a convention-heavy framework genuinely reduces cognitive load and mistakes.

Use this approach when:

  • You have a clear, bounded service
  • Performance is a real requirement, not a premature optimization
  • Your team is comfortable owning infrastructure decisions
  • You want to avoid framework upgrade pain

Reach for FastAPI (or even Django REST Framework) when:

  • You're moving fast and need conventions
  • Your team is less experienced with async Python
  • You need admin interfaces, auth flows, and CRUD scaffolding

Final Thoughts

The Python ecosystem in 2026 has never been better for composable API development. Libraries like Pydantic v2 and Starlette's routing primitives are genuinely production-grade components, not toys. The "no framework" approach isn't a rejection of FastAPI or Django — it's a recognition that those frameworks are themselves built from composable libraries, and sometimes you want to start one level lower.

Ready to build your first frameworkless API? Start with the minimal stack above, pick one endpoint to implement end-to-end, and run your tests. The architecture clarity you gain in that first hour will pay dividends for the life of the service.

If you found this useful, share it with your team or drop it in your Slack channel for the next time someone asks "do we really need all of FastAPI for this?" — because sometimes the answer is no, and now you know what to reach for instead.