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

推荐订阅源

L
LINUX DO - 最新话题
V
Visual Studio Blog
博客园 - 司徒正美
小众软件
小众软件
量子位
J
Java Code Geeks
美团技术团队
Latest news
Latest news
T
Threatpost
V
Vulnerabilities – Threatpost
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
酷 壳 – CoolShell
酷 壳 – CoolShell
C
CERT Recently Published Vulnerability Notes
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Security Latest
Security Latest
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
大猫的无限游戏
大猫的无限游戏
I
Intezer
S
Securelist
TaoSecurity Blog
TaoSecurity Blog
A
Arctic Wolf
罗磊的独立博客
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Cisco Blogs
V2EX - 技术
V2EX - 技术
W
WeLiveSecurity
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
NISL@THU
NISL@THU
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Project Zero
Project Zero
L
LINUX DO - 热门话题
博客园 - Franky
WordPress大学
WordPress大学
月光博客
月光博客
PCI Perspectives
PCI Perspectives
L
Lohrmann on Cybersecurity
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园 - 聂微东
博客园 - 三生石上(FineUI控件)
有赞技术团队
有赞技术团队
Jina AI
Jina AI
爱范儿
爱范儿
博客园 - 叶小钗
T
Threat Research - Cisco Blogs
IT之家
IT之家
Security Archives - TechRepublic
Security Archives - TechRepublic
V
V2EX
博客园_首页
宝玉的分享
宝玉的分享

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
Cursor-Driven Development in FastAPI: Using AI to Generate Type-Safe API Schemas and Catch Contract Breaks Before Deployment
Ugur Aslim · 2026-05-31 · via DEV Community

Ugur Aslim

Cursor-Driven Development in FastAPI: Using AI to Generate Type-Safe API Schemas and Catch Contract Breaks Before Deployment

API contracts break silently. Your React 19 frontend calls POST /users expecting { id: string; email: string }, but your FastAPI backend shipped { userId: number; userEmail: string }. The request succeeds. The response doesn't match. Your frontend crashes in production, and you spend three hours in an incident call figuring out why a perfectly typed TypeScript component is receiving undefined properties.

I've lived this exact nightmare twice on CitizenApp—once before we shipped, once after. The second time cost us a customer's trust and three hours of developer velocity.

The fix isn't better testing or more code review. It's treating your API contract as the single source of truth and using Claude to generate both sides of it from natural language specifications, then validating that they match in CI before deployment. This is cursor-driven development done right: not mindless boilerplate generation, but intelligent contract enforcement that catches type mismatches across language boundaries.

Why This Matters More Than You Think

Most full-stack developers reach for AI to generate TypeScript components or FastAPI route handlers. That's fine. But the real power is forcing your frontend and backend to negotiate a contract before either side exists. When you do this correctly:

  1. Type safety propagates both directions. A TypeScript type change doesn't silently break your Python backend.
  2. Breaking changes fail CI, not production. You catch the moment a contract changes before it ships.
  3. Documentation is generated, not written. Your API spec is always in sync because it's the source of truth.
  4. Onboarding new developers becomes faster. They read the natural language spec, see the contract, and understand the system without hunting through six Slack threads.

I prefer this approach because it forces discipline. Too many teams use AI as a shortcut to avoid thinking about their API design. This pattern does the opposite: it requires you to think first, validate second.

The Pattern: Spec → Contract → Validation

Here's how it works on CitizenApp:

  1. Write a natural language specification (plain English).
  2. Ask Claude to generate a Pydantic schema + FastAPI route stub.
  3. Ask Claude to generate a matching TypeScript type + React hook for that endpoint.
  4. Add a CI step that validates the TypeScript types match the Pydantic schema via introspection.
  5. If they don't match, the build fails. Deliberately.

Let's build this end-to-end.

Step 1: The Natural Language Spec

Feature: User Profile Update
Description: Allow authenticated users to update their profile metadata.
Fields: firstName (string, required), lastName (string, required), bio (string, optional, max 500 chars)
Validation: firstName and lastName must be at least 2 characters
Response: Returns updated user object with id, email, firstName, lastName, bio, updatedAt
Auth: Requires valid JWT in Authorization header

This goes in a file: specs/user-profile-update.md

Step 2: Claude Generates the Backend Contract

Prompt your Cursor AI agent (or use Anthropic's API directly):

Given this spec, generate a FastAPI route with Pydantic schema. 
Use SQLAlchemy ORM patterns. 
Include validation decorators.
Output ONLY Python code, no explanation.

[paste spec here]

Claude outputs something like:

# schemas.py
from pydantic import BaseModel, Field, field_validator

class UserProfileUpdateRequest(BaseModel):
    firstName: str = Field(..., min_length=2, max_length=100)
    lastName: str = Field(..., min_length=2, max_length=100)
    bio: str | None = Field(None, max_length=500)

    @field_validator("firstName", "lastName")
    @classmethod
    def validate_names(cls, v):
        return v.strip()

class UserProfileResponse(BaseModel):
    id: str
    email: str
    firstName: str
    lastName: str
    bio: str | None
    updatedAt: str  # ISO 8601

    class Config:
        from_attributes = True

# routes.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from .schemas import UserProfileUpdateRequest, UserProfileResponse
from .db import get_db
from .auth import get_current_user

router = APIRouter()

@router.put("/users/profile", response_model=UserProfileResponse)
async def update_user_profile(
    request: UserProfileUpdateRequest,
    current_user = Depends(get_current_user),
    db: Session = Depends(get_db),
):
    user = db.query(User).filter(User.id == current_user.id).first()
    if not user:
        raise HTTPException(status_code=404, detail="User not found")

    user.firstName = request.firstName
    user.lastName = request.lastName
    if request.bio is not None:
        user.bio = request.bio

    db.commit()
    db.refresh(user)
    return user

You review this, tweak it if needed, and commit it. This is now your source of truth.

Step 3: Claude Generates the Frontend Contract

Different prompt:

Given this API spec and the Pydantic schemas below, generate:
1. TypeScript types matching the schemas (use zod or ts-pattern if validation needed)
2. A React 19 hook using useAsync or similar pattern

Use TanStack Query for mutations if appropriate.
Assume JWT is in Authorization header (handled by interceptor).

Pydantic schema:
[paste schema here]

API spec:
[paste spec here]

Claude outputs:

// types/user.ts
export interface UserProfileUpdateRequest {
  firstName: string;
  lastName: string;
  bio?: string;
}

export interface UserProfileResponse {
  id: string;
  email: string;
  firstName: string;
  lastName: string;
  bio?: string;
  updatedAt: string;
}

// hooks/useUpdateUserProfile.ts
import { useMutation, useQueryClient } from "@tanstack/react-query";

export function useUpdateUserProfile() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (
      data: UserProfileUpdateRequest
    ): Promise<UserProfileResponse> => {
      const response = await fetch("/api/users/profile", {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
        body: JSON.stringify(data),
      });

      if (!response.ok) {
        throw new Error(`Failed to update profile: ${response.statusText}`);
      }

      return response.json();
    },
    onSuccess: (data) => {
      queryClient.setQueryData(["user"], data);
    },
  });
}

Step 4: Contract Validation in CI

This is where the magic happens. Create a Python script that introspects both:

# scripts/validate_contracts.py
import json
import subprocess
import sys
from typing import Any

def get_pydantic_schema(module_path: str, class_name: str) -> dict[str, Any]:
    """Extract JSON schema from Pydantic model"""
    import importlib.util
    spec = importlib.util.spec_from_file_location("module", module_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    model_class = getattr(module, class_name)
    return model_class.model_json_schema()

def get_typescript_types(file_path: str) -> dict[str, Any]:
    """Parse TypeScript types using TypeScript compiler API"""
    result = subprocess.run(
        ["npx", "ts-json-schema-generator", "--path", file_path, "--type", "*"],
        capture_output=True,
        text=True,
    )
    return json.loads(result.stdout)

def validate_contract(python_schema: dict, ts_schema: dict) -> bool:
    """Ensure Python and TypeScript schemas match"""
    py_props = python_schema.get("properties", {})
    ts_props = ts_schema.get("properties", {})

    # Check all Python props exist in TypeScript
    for key, py_prop in py_props.items():
        if key not in ts_props:
            print(f"❌ Missing in TypeScript: {key}")
            return False

        # Map Python types to TypeScript
        py_type = py_prop.get("type")
        ts_type = ts_props[key].get("type")
        if py_type != ts_type:
            print(f"❌ Type mismatch for {key}: Python={py_type}, TS={ts_type}")
            return False

    return True

if __name__ == "__main__":
    py_schema = get_pydantic_schema("app/schemas.py", "UserProfileUpdateRequest")
    ts_schema = get_typescript_types("src/types/user.ts")

    if not validate_contract(py_schema, ts_schema):
        sys.exit(1)

    print("✅ Contract validated")

Add this to your GitHub Actions workflow:

- name: Validate API contracts
  run: python scripts/validate_contracts.py

- name: Run tests
  run: pytest app/ && npm test

Now, if someone changes a Pydantic field from str to int without updating the TypeScript type, the build fails before merging. This has saved us countless production incidents.

Gotcha: Schema Drift in Optional Fields

This burned me hard: I made a field optional in Pydantic (bio: str | None) but forgot to mark it optional in TypeScript (bio: string instead of bio?: string). The validation passed because my naive script only checked required fields.

The fix: validate both presence and optionality:


python
def validate_contract(python_schema: dict, ts_schema: dict) -> bool:
    py_required = set(python_schema.get