今日已更新 84 条资讯 | 累计 37333 条内容
关于我们

标签:#fastapi

找到 22 篇相关文章

开发者

Day 7 & 8: Python Full Stack Development

Day 7 & 8 of learning Python Full Stack Development, yesterday and today I have started taking an notes for my project ideas and studying about API. As I'm going to started my project, reading some SRS, architecture and features involving in my project and side by side I was learning fastAPI

2026-08-26 原文 →
AI 资讯

Free AI App Builder with Backend: FastAPI Microservice Guide

If you need a free AI app builder with backend to get a FastAPI microservice running today, you can do it with a handful of platforms that bundle hosting, a database, and auth for zero cost. The catch is that the free tiers have hard limits, and they expose the same failure modes you’ll hit in production if you’re not careful. Below I walk through the exact steps, show the code that works, compare the popular builders, and explain how to transition to a production-grade stack when the free tier starts to choke. What free AI app builder platforms include backend services? The short answer is: Cursor , Bolt , and Lovable all ship with a “one-click deploy” that creates a container, wires up a PostgreSQL instance, and adds optional OAuth. They are marketed as “no-code AI app builders,” but you can drop in any Dockerfile – including one that runs FastAPI – and they’ll handle the rest. Platform Backend offering Free tier limits Auth support Cursor Managed container + Postgres 13 500 MB RAM, 1 CPU, 100 k requests/mo Google, GitHub, email Bolt Container + SQLite (upgrade to Postgres) 256 MB RAM, 0.5 CPU, 50 k requests/mo Magic link, JWT Lovable Container + MySQL 5.7 300 MB RAM, 1 CPU, 75 k requests/mo Email/password, OAuth All three let you push a Git repo and they rebuild automatically. That’s the “free AI app builder with backend” you’re after – you get a place to run your FastAPI code without paying for a VM. How do I build a FastAPI AI microservice and deploy it with a free builder? The first thing most builders break on is the cold-start latency of a Python container that pulls a large model at import time. I’ve been bitten by this on Cursor: the first request took 30 seconds, then timed out because the free tier caps request time at 15 seconds. The fix is to load the model lazily or move it to a separate worker. Below is a minimal FastAPI app that calls Claude via the anthropic SDK. The code fits in a 30-line file and works on any of the three platforms. # main.py fro

2026-08-25 原文 →
AI 资讯

Node.js Express vs. Python FastAPI: Which Should You Choose in 2026?

Node.js Express vs. Python FastAPI: The Definitive Guide for Choosing Your Next Backend Choosing a backend framework used to be simple. If you liked JavaScript, you built with Express. If you liked Python, you went with Flask or Django. But the landscape has fundamentally shifted. With the explosion of AI, machine learning, and strict type safety, Python FastAPI has emerged as a powerhouse alternative to the traditional JavaScript runtime. Meanwhile, Node.js Express remains the unopinionated king of the enterprise web. If you are starting a new project today, which one should you choose? Let’s break down the technical trade-offs, developer experience, and code structures of both frameworks. 🚀 The Core Philosophy Node.js Express: The Minimalist Canvas Express is a minimalist, unopinionated framework. It doesn't care how you structure your folders, how you validate data, or how you handle errors. It gives you a robust set of HTTP tools and steps out of your way. The Catch: You have to build or install your own solutions for data validation, ORM mapping, and API documentation. Python FastAPI: The Automated Powerhouse FastAPI is built on modern Python 3.8+ features like type hints and asynchronous ASGI (asyncio). It is highly opinionated about data handling, leveraging Pydantic to automate input validation and schema serialization. The Catch: It forces you into a specific way of handling data types from day one, which can feel restrictive if you prefer absolute freedom. 📊 Feature Breakdown Feature Node.js Express Python FastAPI Language JavaScript / TypeScript Python Data Validation Manual / Third-Party (Zod, Joi) Native via Pydantic API Docs Manual Setup (Swagger UI plugin) Automatic (Interactive Swagger UI & ReDoc) Best For Real-time I/O, WebSockets, Full-stack JS AI/ML APIs, Data pipelines, Type-safe apps 🛠️ Code Comparison: Creating a Validated POST Route Let’s look at how both frameworks handle a common task: creating a POST endpoint that accepts an item, validates

2026-08-24 原文 →
AI 资讯

Iran Doesn't Need to Mine Hormuz — Your requirements.txt Is Already Rigged

Iran Doesn't Need to Mine Hormuz — Your requirements.txt Is Already Rigged Every headline you've read this week is a diversion. The Strait of Hormuz is not the target. You are. And you have been for months, possibly years, while you retweeted tanker tracking maps and debated whether Brent crude would touch $150. Iranian state-sponsored groups — OilRig, APT33, MuddyWater, Agrius — did not spend the last decade pivoting to cloud infrastructure so they could watch you panic about a waterway. They did it so they could own your build pipeline while you were distracted. And they have. This is not speculation. CISA Advisory AA24-038A explicitly maps Iranian APT campaigns against U.S. and allied critical infrastructure to cloud identity, Kubernetes targets, and software supply chains. Not SCADA. Not PLCs. Your kubectl binary. Your Helm charts. That FastAPI microservice running payment webhooks that you deployed on a Friday and haven't touched since March. The Revolutionary Guard does not need a mine. They need a maintainer who hasn't updated python-jose in fourteen months. The Theater and the Operation You watched the Strait. They watched your CI/CD. Geopolitical analysis is a spectator sport for infrastructure engineers, and Iranian cyber command is the bookie. While your LinkedIn feed filled with satellite imagery and retired admirals explained chokepoint logistics, the actual operation ran silently against: Public Helm charts with hardcoded cluster-admin ServiceAccounts FastAPI services with python-multipart handling unbounded file uploads on single-threaded Uvicorn workers .kube/config files exfiltrated from developer laptops in a dev-legacy namespace that predates your current CTO Terraform state stored in a single S3 bucket with versioning disabled and a policy written by someone who left in 2021 The Hormuz closure narrative is Information Operations . The closure of your API gateway due to an unpatched ASGI memory exhaustion vulnerability is the kinetic effect. You a

2026-08-21 原文 →
AI 资讯

I Built a Signed Webhook Receiver for Cross-Server Communication

Sometimes your application can reach an external service from one server, but not from another. I ran into this problem while working on one of my projects. I needed my server in Iran to communicate with Telegram, but the connection wasn't reliable from inside Iran. Instead of moving the whole application, I built a small intermediate service: Signed Webhook Receiver It is a lightweight FastAPI service that receives requests signed with an RSA private key and verifies them using the corresponding public key before processing them. Your Server | | RSA Signed Request v Webhook Receiver | | HTTP Request v External Service The receiver can be useful for: Secure server-to-server communication Webhooks and internal APIs Acting as a controlled proxy/gateway Connecting servers across different network environments Payment integrations where a provider requires requests from an Iranian IP For example, if your main application is hosted outside Iran but a payment gateway only accepts requests from Iranian IP addresses, an Iranian server can act as the intermediate gateway: Foreign Server | | Signed Request v Iranian Gateway Server | v Payment Gateway The important part is that this isn't an open proxy. Requests can be authenticated and the gateway can be restricted to specific operations and destinations. The project is built with Python, FastAPI, Cryptography, Docker, and Traefik and is open source. View the project on GitHub I also wrote more technical notes and development articles on my website: Building a Secure Webhook Receiver for Server-to-Server Communication | CyberHuginn

2026-08-11 原文 →
AI 资讯

Beyond Login: Building a Production Authentication Lifecycle in FastAPI

Authentication is often presented as a short sequence: Accept a username and password. Return a JWT. Protect a few endpoints. That is enough for a tutorial, but it is not an authentication lifecycle. Real applications must also answer harder questions: How is an email address verified without storing a reusable secret? What happens to existing sessions after a password reset? Can a user see and revoke a lost device? How do we prevent a rotated refresh token from being replayed? How should TOTP secrets and recovery codes be stored? How can an OIDC identity be linked without trusting email matching? I explored those questions while building FastAPI Production API v1.2.0 , a backward-compatible authentication lifecycle release for an open-source FastAPI backend foundation. This article explains the design decisions behind it—not just the endpoints that were added. 1. Model lifecycle tokens as scoped, single-use credentials Email verification and password recovery look similar from the outside: send a link, receive a token, and update an account. Treating them as interchangeable, however, creates unnecessary risk. The release uses account-action tokens with four important properties: Random: the token is generated as an opaque secret rather than derived from user data. Scoped: a verification token cannot be used as a password-reset token. Expiring: every token has a short, configurable lifetime. Single use: confirmation atomically marks the token as consumed. Only a hash of the token is persisted. The original value exists only long enough to be delivered to the user. This gives email verification and password reset a shared security primitive without making their policies identical. The main endpoints are: POST /auth/email-verification/request POST /auth/email-verification/confirm POST /auth/password-reset/request POST /auth/password-reset/confirm Both request operations return uniform responses. A caller should not be able to determine whether an email belongs to an a

2026-08-09 原文 →
AI 资讯

Building a Modern Rate Limiter and DDoS Protection Library for Python

Rate limiting is one of those features every production API eventually needs. Whether you're building a public REST API, a WebSocket service, or an authentication endpoint, you'll eventually face problems like: Credential stuffing Brute-force attacks API abuse Bots scraping your endpoints Unexpected traffic spikes Most applications solve this with a simple request counter. But after building several APIs with Django, FastAPI, and Flask, I realized that production traffic requires much more than "X requests per minute." That observation led me to build drogue , an open-source Python library for rate limiting and traffic protection. The Problem Traditional rate limiting is straightforward: Allow 100 requests per minute. This works well for many cases, but real-world applications quickly expose its limitations. For example: A distributed attack can remain below the per-IP limit. A bot can rotate through proxies. WebSocket connections often require different handling than HTTP requests. Different endpoints need different protection strategies. I wanted a system that could go beyond simple request counting. Design Goals From the beginning, I focused on a few principles. 1. Clean framework integration I didn't want endpoint functions filled with framework-specific plumbing. Instead, the library should feel like a natural extension of the framework. from fastapi import FastAPI from drogue.adapters.fastapi import DrogueLimiter app = FastAPI () limiter = DrogueLimiter ( app , default_limits = [ " 100/minute " ]) @app.get ( " /users " ) @limiter.limit ( " 10/minute " ) async def users (): return { " status " : " ok " } No additional request objects. No complicated middleware configuration. Minimal boilerplate. Multiple Rate Limiting Algorithms Different applications require different algorithms. Instead of supporting only one approach, drogue includes multiple options: Token Bucket Sliding Window Fixed Window Each has different trade-offs between accuracy, burst handling, and

2026-07-29 原文 →
AI 资讯

Decoupled User Management in Python

Hands-On tests with 'UserHarbor' and IBM Bob: A Modular Approach to Python User Authentication and Permissions Introduction When evaluating open-source libraries for core application infrastructure - such as authentication, session management, and fine-grained Role-Based Access Control (RBAC) - getting hands-on with a complete reference application is invaluable. This is especially true for libraries aiming to be framework-agnostic, promising flexibility but requiring more explicit wiring. Recently, I wanted to explore UserHarbor ( github.com/userharbor/userharbor ), a lightweight Python user-management library designed without direct coupling to any web framework or database toolkit. Rather than manually bootstrapping a new project, setting up the SQLite database, and writing boilerplate code to explore every edge of the library, I used IBM Bob , to scaffold and implement an end-to-end reference demonstration integrated with FastAPI , SQLAlchemy for persistence, and SMTP (or a local console fallback) for transactional emails. The goal was to rapidly test UserHarbor's entire feature lifecycle - registration, email verification, session tokens, optional authentication, RBAC guards, password resets, and account deletion, which I personally find really useful. These capacities could be implemented in many applications and ease the phase of user registration, email validation etc… This post details the architecture built, highlights the key implementation logic, and illustrates how easily a decoupled core can be integrated into a modern web stack. UserHabor (from official GitHub repostory) Image from official project's repository Project status: UserHarbor is currently in an early stage of development. The API may change frequently. The library is not ready for production use yet . UserHarbor is a framework-agnostic Python library for user account management. Its goal is to provide a simple, stable, and framework-independent interface for common user-related operations:

2026-07-28 原文 →
AI 资讯

Why I Put Mirth Connect in Front of FastAPI Instead of Parsing HL7 in Python

When I started building my Maternity HL7-to-FHIR Pipeline , my first instinct was to do everything in Python. Parse the HL7 message, map the fields, validate the FHIR resource, persist it, all in one FastAPI service. It was clean. It was simple. It was wrong. The "Just Parse It in Python" Phase My initial architecture looked like this: Hospital System --MLLP--> Python Script --> HAPI FHIR Server I used python-hl7 to split messages on | and count field positions. For a single ADT^A01 (patient admission) message, it worked fine. I could pull the patient name from PID-5 , the MRN from PID-3 , the gender from PID-8 , and build a FHIR Patient resource from it. Then I tried a real-ish maternity workflow (an admission, an order, and a set of vitals) and things fell apart quickly. Five Problems That Changed My Mind 1. MLLP Is Not HTTP Hospital systems don't send HL7 over HTTP. They send it over MLLP (Minimum Lower Layer Protocol), which is a TCP socket protocol with specific framing bytes ( \x0b at the start, \x1c\x0d at the end). The sender expects an ACK or NACK response in HL7 format, not an HTTP status code. Building an MLLP listener in Python is possible . Libraries like aioml7 exist. But you're now maintaining a custom TCP server alongside your HTTP API server, handling connection pooling, timeouts, and HL7 acknowledgment generation. That's a lot of infrastructure code that has nothing to do with your actual transformation logic. Mirth Connect handles MLLP natively. You point it at a port, it listens, it parses, it ACKs. Done. One config screen, no custom code. 2. HL7 Parsing Is Messier Than It Looks The pipe-delimited format looks simple: PID|1||1234567^^^MRN||TEST^PATIENT^MARY^^MS||19920315|F|||14 SAMPLE ST^^SYDNEY^NSW^2000^AU But consider: Component separators : PID-5 is TEST^PATIENT^MARY^^MS , which is family, given, middle, suffix (empty), prefix. Miss the empty suffix and your prefix ends up as the suffix. Repeating fields : PID-3 can contain multiple identifier

2026-07-26 原文 →
AI 资讯

A FastAPI Agent Template Is Not Production-Ready Until Task Ownership Crosses Every Layer

Vercel published an OpenAI Agents SDK with FastAPI template on July 17, 2026. A template can remove setup work, but successful generation is not the production boundary that usually breaks. Task ownership is. Primary source: Vercel template, “OpenAI Agents SDK with FastAPI” . Before adopting any agent starter, I would add one vertical test: Alice must be able to create and cancel her task; Bob must not be able to read, stream, or cancel it—even if he guesses the task ID. State the cross-layer contract UI -> POST /tasks -> ownership row -> worker UI <- GET /tasks/:id <- authorization <- state UI <- event stream <- authorization <- events UI -> POST /tasks/:id/cancel -> authorization -> cancellation Use explicit states: queued -> running -> succeeded -> failed queued|running -> cancelling -> cancelled The database, API response, stream, and UI must agree on the same task and owner. Minimal schema create table tasks ( id text primary key , owner_id text not null , state text not null check ( state in ( 'queued' , 'running' , 'succeeded' , 'failed' , 'cancelling' , 'cancelled' )), created_at text not null , updated_at text not null , revision integer not null default 0 ); create table task_events ( task_id text not null , revision integer not null , kind text not null , payload text not null , primary key ( task_id , revision ) ); Do not derive ownership from a browser-supplied field. Resolve the authenticated principal on the server and store it when creating the task. FastAPI authorization seam from fastapi import Depends , FastAPI , HTTPException app = FastAPI () def current_user (): # Replace with verified session/JWT middleware. return { " id " : " alice " } def load_owned_task ( task_id : str , user = Depends ( current_user )): task = db_get_task ( task_id ) # application function if task is None or task [ " owner_id " ] != user [ " id " ]: # Avoid revealing whether another user's task exists. raise HTTPException ( status_code = 404 , detail = " task not found " )

2026-07-17 原文 →
AI 资讯

Did you ever face "stale singleton httpx connection" and "cold-start connection problem" problem, Well I did tonight.

It is been while I am learning and build around FastAPI. So there is a project where I was thinking how to add this new feature over exiting one. Like what changes I need to make in database which need to be reflected in my backend and frontend. I already lunched the web locally. Problem started When I when back to the web and reload it it shows this error: ERROR: ConnectTimeout: Unauthorized 401. I was like what? Why? I thougth there is some issue with login endpoint or refresh token function. When i did some debugging and found some new information which is: "Either Supabase's edge/pooler (or OS, or an intermediate proxy/NAT) silently kills those idle connections server-side after some timeout but client-side pool doesn't know that." As I was doing nothing in become idle state so to save the resources server side silently close that particular connection. So I came back and try to connect it give this error. First thought come it my mind after this was there should be a way to automatically check this idle state and if user was in ideal state then create a new connection. Proposed Solutions After a while I come up with these solution: Calculate the Idle time: if it is more then server connection timeout then establish new connection. Retry logic: retry once on the specific connection errors. I thought this will work but This again give me error then this new issue I faced. Cold-start connection problem There is something call dual-stack (IPv4 and IPv6) networks and Happy Eyeballs is a network mechanism which automatically move to IPv4 connection if IPv6 fails. But supabase-py uses httpx and it doesn't support Happy Eyeballs. So in first try after the connection time out it try to establish IPv6 connection which is not routeable in most Pakistani ISPs and ultimately it fails and wait for timeout. There is no way to try it again for IPv4. So we have to do it manually. So this error help me to learn many thing in process. Share your thoughts.

2026-07-09 原文 →
AI 资讯

Hardening my own Nmap web UI: the security holes I shipped, and what actually saved me

I built a web front end for an Nmap-based port scanner: a FastAPI backend, a React dashboard, background scan jobs, a plugin system. It worked. Then I sat down and audited it like an attacker would — and found a stack of real weaknesses, plus a lesson in why you verify an exploit before you call it one. This is the honest version: the holes I found, the unauthenticated-RCE chain I thought I had, why it didn't actually fire, and the hardening I shipped anyway. Repo: https://github.com/DipesThapa/PortScanner This is my own project, audited and fixed by me. No third-party systems were touched. Scanners are dual-use — only ever point one at hosts you own or are authorised to test. Hole 1: no authentication, anywhere The foundation: every API route and the /ws/status WebSocket were open. No API key, no session. The Dockerfile bound 0.0.0.0:8000 and ran as root. Anyone who could reach the port could drive scans, hit the upload endpoint, and read every job's logs. api_router = APIRouter () # no dependencies — fully open This is the real, unambiguous problem. Everything below is only interesting because it sat behind no auth. Hole 2: an upload endpoint that allowlisted its own files Deep-dive follow-up commands ran against an allowlist — good instinct. But an upload endpoint wrote a file, chmod +x 'd it, and then added it to that same allowlist: for item in scripts_dir . glob ( " * " ): if item . is_file (): allowed . add ( str ( item . absolute ())) # upload authorises itself An allowlist any input can extend isn't an allowlist. This is a genuine design footgun. Hole 3: the RCE I thought I had — and why it didn't fire Here's the chain I got excited about: the scan target flows toward Nmap's argv, and it's subprocess.run(..., shell=False) . No shell injection — but you don't need a shell to abuse Nmap. If a target became --script=/uploaded.nse , Nmap would load and run that NSE (Lua) script, and NSE can call os.execute . Upload a malicious .nse (Hole 2), get Nmap to load it

2026-07-07 原文 →
AI 资讯

Stop Overtraining: Build an AI Agent to Auto-Sync Your Fitness Plan with Your Heart Rate (LangGraph + Notion)

We’ve all been there. You have a "Leg Day" scheduled in your Notion database, but you woke up feeling like a truck hit you. Your Apple Watch says your Heart Rate Variability (HRV) is in the gutter, but your rigid calendar doesn't care. Usually, you’d either push through and risk injury or manually move cards around in Notion—which is a friction-filled nightmare. In this tutorial, we are building a Self-Optimizing Health Agent using LangGraph , Notion API , and HealthKit . This agent acts as a closed-loop system: it analyzes your physiological recovery data, reasons about your physical state using an LLM, and automatically rewrites your training schedule. By mastering AI agents , LLM orchestration , and fitness automation , you’ll turn your static "To-Do" list into a dynamic "Should-Do" list. 🥑 The Architecture: The Bio-Feedback Loop Using LangGraph , we can treat our fitness logic as a state machine. Unlike a linear script, a graph allows our agent to decide whether it needs to fetch more context (like yesterday's sleep) before making a final decision on your workout. graph TD Start((Start)) --> FetchHRV[Fetch HRV Data via HealthKit] FetchHRV --> CheckRecovery{LLM: Analyze Recovery} CheckRecovery -- "Low Recovery (Fatigued)" --> ModifyNotion[Action: Downgrade Workout Intensity] CheckRecovery -- "High Recovery (Fresh)" --> KeepNotion[Action: Maintain/Boost Intensity] ModifyNotion --> UpdateNotion[Update Notion Page] KeepNotion --> UpdateNotion UpdateNotion --> End((Done)) style CheckRecovery fill:#f96,stroke:#333,stroke-width:2px style FetchHRV fill:#bbf,stroke:#333 Prerequisites Before we dive into the code, ensure you have: Python 3.10+ LangChain & LangGraph installed ( pip install langgraph langchain_openai ) Notion Integration Token (with access to your workout database) HealthKit SDK (Note: Since we are in a Python environment, we'll simulate the HealthKit fetcher, though in a real-world scenario, this would be bridged via a FastAPI endpoint from an iOS app). St

2026-07-05 原文 →
AI 资讯

Shifting Left: How TDD Became the Foundation of SokoFlow's Core Engine

SokoFlow Build Log — Month 1 of 4 Last semester I set out on a new strategic plan to level up my software development skills through deliberate, project-based learning. That work produced one of the most ambitious things I've built so far: Sim-Pesa , a local-first transactional appliance that lets developers working in the M-Pesa ecosystem test and simulate STK Push workflows entirely on their own machines, without depending on the Daraja sandbox. I documented that build in 16 weekly posts, which you can find here . This semester, the focus shifts — from fintech foundations to cloud-native integration and real-world systems. The flagship project is SokoFlow , a conversational ERP for small Kenyan shopkeepers to track inventory and record sales entirely through WhatsApp chat. No app to download, no training session required — just natural language. Where Sim-Pesa lived in a controlled, predictable transactional world, SokoFlow steps into the mess of cloud-native reality: third-party API failures, webhook signature verification, the statelessness of HTTP, and container orchestration. The target audience shifts too — Kenyan SMEs operating on infrastructure that is often unreliable by design, not by exception. It's an ambitious project, but the goal was always to learn as much as possible from it. With the plan in place, I got to work. 1. The Vision of a Headless ERP The first real question I had to answer before writing a line of code: what does "headless" actually mean? Headless architecture decouples the frontend — the "head," or user interface — from the backend, the "body" that holds the data and business logic. A conventional ERP bundles both: backend plus a dashboard or UI on top. A headless ERP, by contrast, is just the engine. The brain. There's no built-in screen. So how do users interact with a system that has no interface of its own? SokoFlow doesn't actually care. It could be: WhatsApp SMS A web app A mobile app A voice assistant In this case, the "frontend

2026-06-30 原文 →
AI 资讯

"You code. We cloud." — Why the Cleverest FastAPI Hosting Headline Still Misses

There's a headline pattern that feels like sharp marketing writing but quietly costs conversions. "You code. We cloud." It's clever. The parallel structure is tight. It names a clear division of labor. But it describes the service delivery model , not the developer outcome — and those are different things to someone scanning a landing page in five seconds. The audit fastapicloud.com is a managed hosting product built specifically for FastAPI developers. The hero H1 is: "You code. We cloud." On the surface this reads as clean, confident B2B positioning. In practice, it names the mechanism: You = who does the coding We cloud = who handles the infrastructure What's missing is the output. What does the developer actually walk away with? The gap (mechanism-first H1): The headline describes the service model without anchoring it in the developer outcome. The visitor has to make a three-step inference: "they handle the cloud" → "that means I don't do ops" → "so my app gets to production without a week of DevOps work." In five seconds of scrolling, most won't finish that chain. The headline earns a nod of recognition. It doesn't earn the scroll. The fix One line changes the frame completely. Before: "You code. We cloud." After: "Your FastAPI app is live in production — zero config rabbit holes, zero deploy-day surprises." The rewrite keeps the same promise — they handle the infrastructure — but anchors it in the developer's world. The outcome (app in production) is first. The pain points ("config rabbit holes," "deploy-day surprises") are the exact things a FastAPI developer has already lived through. "Zero config rabbit holes" names the experience of spinning up a production server for the first time. "Zero deploy-day surprises" names the dread: the Sunday night broken deploy that wasn't caught in staging. Any backend developer who reads that line knows exactly what it's describing. The mechanism (managed cloud, they handle ops) is still implied. But the headline earns the

2026-06-23 原文 →
AI 资讯

From Pixels to Proteins: Building a Precise Dietary Analysis System with GPT-4o and SAM

Have you ever tried to track your calories by manually searching for "half-eaten avocado toast" in a database? It’s a nightmare. While basic AI Computer Vision can identify an "apple," traditional models often fail at the granular level—distinguishing between 100g and 250g of pasta or identifying hidden toppings in a complex salad. In this tutorial, we are building a high-precision food nutrition AI engine. By combining the Segment Anything Model (SAM) for pixel-perfect object isolation and GPT-4o Vision for multi-modal reasoning and volume estimation, we can transform a simple smartphone photo into a detailed nutritional report. If you’re looking to dive deeper into production-grade AI patterns, I highly recommend checking out the advanced engineering guides at WellAlly Blog , which served as a major inspiration for this architecture. 🏗️ The Architecture: A Hybrid Vision Pipeline To achieve high accuracy, we don't just throw an image at an LLM. We use a "Segment-then-Analyze" pipeline. This ensures the LLM focuses on specific regions of interest (ROIs) rather than getting distracted by the background. graph TD A[User Uploads Food Image] --> B[Pre-processing with OpenCV] B --> C[SAM: Segment Anything Model] C --> D{Multi-Object Masking} D -->|Mask 1: Protein| E[GPT-4o Vision Reasoning] D -->|Mask 2: Carbs| E D -->|Mask 3: Veggies| E E --> F[Nutrient Mapping & Volume Estimation] F --> G[FastAPI Response: JSON Schema] G --> H[Final Dashboard] 🛠️ Prerequisites Before we start, ensure you have your environment ready: Python 3.10+ GPT-4o API Key (OpenAI) SAM Weights ( sam_vit_h_4b8939.pth ) Tech Stack : FastAPI , OpenCV , PyTorch , segment-anything 🚀 Step-by-Step Implementation 1. Object Segmentation with SAM First, we use Meta’s SAM to generate masks. This allows us to "cut out" each individual food item. import numpy as np import cv2 from segment_anything import sam_model_registry , SamPredictor # Initialize SAM sam_checkpoint = " sam_vit_h_4b8939.pth " model_type = "

2026-06-18 原文 →
AI 资讯

FastAPI for AI Engineers - Part 4: Stop Bad Data Before It Breaks Your API (Pydantic and Data Validation)

In the previous article, we connected our FastAPI application to a database using SQLite and SQLAlchemy. We also used classes like: class StudentCreate ( BaseModel ): name : str department : str cgpa : float without fully understanding what was happening behind the scenes. Today, we'll fix that. If you haven't read it check it out: FastAPI for AI Engineers - Part 3: Connecting to a database Ananya S Ananya S Ananya S Follow Jun 6 FastAPI for AI Engineers - Part 3: Connecting to a database # ai # fastapi # python # backend 6 reactions Add Comment 6 min read Why Do We Need Data Validation? Imagine you're building a weather application. A user asks: What is the temperature in Chennai? A valid response might be: 35 or 35°C But what if the API returns: Sunny This is clearly wrong. Temperature should be represented as a number. Even if the value itself is inaccurate, we still know that temperature must be numeric. This is where validation becomes important. Validation allows us to define rules about what data is acceptable before it enters our application. For example: Temperature should be numeric Age cannot be negative CGPA should be between 0 and 10 Email addresses should follow a valid format Without validation, applications can receive invalid data and behave unexpectedly. The Problem Without Validation Consider a student registration API. @app.post ( " /student " ) def create_student ( student ): return student A user could send: { "name" : "Ananya" , "cgpa" : "Excellent" } The API would accept it. But a CGPA should be a number, not text. As applications grow, manually checking every field becomes difficult. We need a better solution. Enter Pydantic Pydantic is a Python library used for data validation. FastAPI uses Pydantic extensively behind the scenes. Instead of manually validating data, we define a schema. from pydantic import BaseModel class Student ( BaseModel ): name : str cgpa : float Now FastAPI knows: name must be a string cgpa must be a floating-point nu

2026-06-09 原文 →
AI 资讯

FastAPI for AI Engineers - Part 3: Connecting to a database

In the previous article, we explored how to build our first CRUD API using FastAPI. While our API worked correctly, there was one major problem. We were storing data inside Python lists, which exist only in memory. If you've ever wondered how applications like Instagram, LinkedIn, or ChatGPT remember information even after a server restart, the answer is simple: databases. In this article, we'll solve the problem of in-memory storage by connecting our FastAPI application to SQLite using SQLAlchemy. If you haven't read the previous post, check it out: FastAPI for AI Engineers - Part 2: Building Your First CRUD API Ananya S Ananya S Ananya S Follow Jun 1 FastAPI for AI Engineers - Part 2: Building Your First CRUD API # ai # backend # fastapi # python 7 reactions Comments Add Comment 4 min read By the end of this article, you'll understand: Why in-memory storage is a problem What SQLite is What SQLAlchemy is How ORM works How to create database tables using Python classes How to perform CRUD operations using a real database The Problem with In-Memory Storage Previously, our application stored students inside a Python list. students = [ { " id " : 1 , " name " : " Ananya " , " department " : " CSE " , " cgpa " : 8.9 } ] This worked for learning CRUD operations. However, consider what happens when the server restarts: FastAPI Server Stops ↓ Python Memory Cleared ↓ All Student Data Lost This is unacceptable in real-world applications. We need a place where data can survive application restarts. This is where databases come in. What is SQLite? SQLite is a lightweight relational database. Unlike MySQL or PostgreSQL, SQLite doesn't require a separate database server. Instead, everything is stored inside a single file. students.db Advantages of SQLite: No installation required Lightweight Easy to learn Perfect for local development Great for small projects For this article, we'll use SQLite. What is SQLAlchemy? Before SQLAlchemy, developers often wrote raw SQL queries. Exampl

2026-06-06 原文 →
AI 资讯

Stop Juggling 5 Tools , Python's uv Does It All (And It's Blazing Fast)

If you've been writing Python for more than a year, you know the ritual. A new project. A fresh terminal. And then: pyenv install 3.12.3 pyenv local 3.12.3 python -m venv .venv source .venv/bin/activate pip install pip --upgrade pip install -r requirements.txt Six commands before you've written a single line of code. And that's if nothing breaks. Enter uv a single binary that replaces pip , virtualenv , pip-tools , pyenv , and pipx . Written in Rust. 10–100x faster than pip. And honestly, one of the most pleasant tools I've used in the Python ecosystem in years. Let's dig into it. What Even Is uv ? uv is a Python package and project manager built by Astral , the same team behind ruff , the linter that everyone switched to and never looked back. The goal is simple: be the Cargo for Python . One tool, one lockfile, no friction. It's a standalone binary with zero Python dependencies, which means it works even before Python is installed. Installing uv # macOS / Linux curl -LsSf https://astral.sh/uv/install.sh | sh # Windows (PowerShell) powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" # Or via pip if you prefer pip install uv Verify: uv --version # uv 0.9.x The Speed Claim Is It Real? Yes. Embarrassingly so. Here's a timed comparison on Apple Silicon (Python 3.14): Operation pip / venv uv Create virtual env ~2 seconds 35 milliseconds Install FastAPI + deps (cold) ~12s ~1.2s Install with warm cache ~8s ~0.1s The warm cache case is where uv really shines it uses a global cache and hard-links packages into environments instead of copying them. If you've installed requests in any previous project, your next project gets it nearly instantly. Starting a New Project This is where uv feels like a completely different world: uv init my-api cd my-api That single command gives you: my-api/ ├── .git/ ├── .venv/ ← already created ├── .python-version ├── pyproject.toml ├── README.md └── main.py No separate python -m venv , no git init , no template c

2026-06-03 原文 →
AI 资讯

Building KindaSeen with FastAPI, Next.js, and PostgreSQL

“Did We Already Watch This?” — Building KindaSeen with FastAPI and Next.js A few months ago, my friends and I kept running into the same question whenever we talked about movies, dramas, anime, or variety shows: “Did we already watch this before?” Sometimes we remembered the title but forgot whether we had finished it. Other times, we completely forgot we had already seen it at all. That simple problem inspired me to build KindaSeen, a full-stack personal media repository designed to help users track and organize the media they’ve consumed in one centralized platform. The goal of the project was not only to create a useful application, but also to gain hands-on experience building a real-world full-stack system with modern web technologies. What KindaSeen Currently Supports User authentication with Supabase CRUD operations for personal media records TMDB-powered search functionality Watchlist system Favorites system Persistent PostgreSQL storage Dockerized backend deployment Separate frontend/backend deployment workflow Tech Stack Frontend Next.js React Tailwind CSS Shadcn/ui Vercel deployment Backend FastAPI PostgreSQL Docker Render deployment External Services Supabase Authentication TMDB API integration One of the main goals of this project was to simulate a more realistic production workflow by using a decoupled frontend/backend architecture instead of building everything inside a single monolithic application. In this article, I’ll share: Why I chose this architecture How I integrated TMDB into the application Challenges I faced during deployment What I Learned From Building KindaSeen Why I Chose This Architecture Instead of building a monolith using Next.js API routes, I decided to decouple the application into a Next.js frontend and a FastAPI backend. This decision was driven by three main factors: AI Compatibility & Future Proofing : While researching the job market, I noticed that most companies building AI products heavily rely on Python. By choosing FastA

2026-06-02 原文 →