r/FastAPI • • Nov 01 '23

Question Following a tutorial and they are showing the modules get auto imported through intellisence on VSCode; however its not working on mine.

1 Upvotes

Anyone have a a solution to this issue?

VScode Settings

{
  "workbench.iconTheme": "material-icon-theme",
  "editor.wordWrap": "bounded",
  "files.autoSave": "afterDelay",
  "prettier.htmlWhitespaceSensitivity": "strict",
  "editor.rulers": [80],
  "explorer.compactFolders": false,
  "editor.minimap.enabled": false,
  "liveServer.settings.donotShowInfoMsg": true,
  "javascript.preferences.quoteStyle": "single",
  "prettier.jsxSingleQuote": true,
  "prettier.singleQuote": true,
  "workbench.colorTheme": "Panda Syntax",
  "editor.formatOnSave": true,
  "editor.formatOnType": true,
  "editor.tabSize": 2,
  "liveServer.settings.donotVerifyTags": true,
  "window.zoomLevel": 1,
  "terminal.integrated.fontFamily": "JetBrains Mono",
  "editor.fontFamily": "JetBrains Mono",
  "editor.fontLigatures": true,
}

r/FastAPI • • Aug 15 '24

Question This site can't be reached message

0 Upvotes

Why am I getting "This site can't be reached" message when I click on the http link?

This is code I am using:

!pip install fastapi uvicorn

from fastapi import FastAPI

from fastapi import FastAPI

app = FastAPI()

u/app.get("/")

def read_root():

return {"Hello": "World"}

import uvicorn

from multiprocessing import Process

def run_uvicorn():

uvicorn.run(app, host="0.0.0.0", port=8000)

if __name__ == "__main__":

p = Process(target=run_uvicorn)

p.start()


r/FastAPI • • Jul 30 '24

Question Need help while deploying FastAPI server in Azure App services

1 Upvotes

When I am trying to run below code in local, it works fine.

params = urllib.parse.quote_plus(
    f'Driver={Driver};'
    f'Server={Server};'
    f'Database={Database};'
    f'Uid=Trabii_BE_GUY;'
    f'Pwd={Pwd};'
    'Encrypt=yes;'
    'TrustServerCertificate=no;'
    'Connection Timeout=30;'
)

# Construct the connection string
conn_str = f'mssql+pyodbc:///?odbc_connect={params}'

engine = create_engine(conn_str)

But when I am trying to deploy using Azure app services it is giving me below error. I have already verified the credentials twice, but don't know what's wrong.

2024-07-30T08:56:12.370094623Z sqlalchemy.exc.InterfaceError: (pyodbc.InterfaceError) ('28000', "[28000] [Microsoft][ODBC Driver 18 for SQL Server][SQL Server]Login failed for user 'Trabii_BE_GUY'. (18456) (SQLDriverConnect)")


2024-07-30T08:56:12.370098023Z (Background on this error at: https://sqlalche.me/e/20/rvf5)

r/FastAPI • • Aug 13 '24

Hosting and deployment Vector databases for webapps

Thumbnail
levelup.gitconnected.com
0 Upvotes

r/FastAPI • • Feb 04 '24

Question Passing a value to @limiter.limit() from the result of a Depends

0 Upvotes

I have a fastapi route with a Depends, like:

index_id: str = Depends(get_index_id)

get_index_id pulls the auth token from the Header, then does a lookup in my DB. I want to use the result of that in my limit() method.

this will allow me to change the rate_limit based on the results of the index_id (doing a separate lookup).

can anybody point me in the right direction for achieving this?


r/FastAPI • • Dec 30 '20

Question Fast API - AJAX Put Method not working

1 Upvotes

Good day - before any critique just wanna say I am new to FastAPI. I need help with the following...I am just trying to do a simple CRUD using bootstrap front-end.

The backend(swagger docs) is working fine....however I am not able to seemingly link front-end component. I am using Postgresql DB.

What I have done:

1- being able to Create Post method and it updates the DB successfully

2- able to get single record from DB - and display on the front-end

What is not working:

3- Update/PUT method

To do still:

4- Delete method

I am using JQuery/Ajax - which might not be the best implementation(understood and agreed) but my intent is to understand how FastAPI works both front-end and backend...

Having said above - I would appreciate if you able to have a look at the issue i logged on SO and provide some feedback please herewith the link https://stackoverflow.com/questions/65419931/fastapi-using-jquery-ajax-put-method-not-working

once working next step for me would be to find a more pydantic manner in which to make same work.

Thanks in advance


r/FastAPI • • Jul 06 '21

Question How to send data through a web socket from an HTTP request?

1 Upvotes

I want to send data to a user through a web socket when some action is performed in an HTTP endpoint. Is there a mechanism to do that with the fast API WebSocket? I had done this earlier with flask and socket-io. I have been looking for implementing this in fast API.

Thanks


r/FastAPI • • Dec 01 '21

Question How to deploy API that has REST and WebSocket? Help

0 Upvotes

Hello all, I am currently in the stage of deployment for my application. Right now the problem that I have is trying to deploy the API. How do I go about this, the API has REST and WebSockets combined. The method of deployment that I plan to use is with AWS's EC2 instances (The free instance at first just to try the application out).


r/FastAPI • • May 19 '21

Question Writing models on fastapi is difficult with sqlalchemy.

0 Upvotes

can anyone recommend better orm similar to django-orm with async support if possible.


r/FastAPI • • Sep 19 '21

Question How to save and retrive RichTextEditor value in Mongodb+FastApi?

1 Upvotes

Frontend site I want to use Rich text editor(bold,italic line etc), I want to store these editor data MongoDb using fastapi. How could I store whole textEditor value in MongoDb and retrive them as a real format?


r/FastAPI • • Dec 04 '21

Question Using an HTML form, how do I access the PUT method?

1 Upvotes

Since there is no HTML <form> PUT method, can someone point me in the correct direction on how to use an HTML form with the app.put() in my API?

Do I just use an app.post() and leave it at that?


r/FastAPI • • Mar 24 '26

pip package We listened. api-shield now has a standalone server, SDK support, and full OpenFeature-compatible feature flags

0 Upvotes

A few days ago I posted here my newly built library for managing route states in FastAPI with maintenance mode, disabling routes, env gating without redeploying. The thread got some great discussion, honest pushback, and a few "why not an API Gateway" comments.

What's changed since that post

The original version only worked as an embedded library inside a single FastAPI app with multi-instance support. If you had multiple services, you had to wire up each one separately with no shared state between them.

That's gone now.

Standalone shield server + SDK

You can now run api-shield as its own server and connect any number of services to it via the SDK. One control plane for your whole fleet, toggle maintenance on a route in service A from the same dashboard that manages service B. No Redis config required unless you want it.

# In each service
from shield.sdk import ShieldSDK

client_sdk = ShieldSDK("http://shield-server:8000")
client_sdk.attach(app)

Feature flags — full OpenFeature spec

This was a requested feature. api-shield now ships with a complete feature flag system built on the OpenFeature specification.

  • Boolean, string, integer, float, and JSON flag types

  • Targeting rules (attribute-based), individual user targeting, percentage rollouts

  • Kill-switch per flag (disable without deleting)

  • Prerequisite flags

  • Segments — reusable groups of users you can reference across flags

  • Scheduled flag changes

You can use our built-in provider or drop in any provider the OpenFeature ecosystem already supports. If your team already uses a provider for something else, it plugs straight in.

engine.use_openfeature()

# Evaluate in a route
ctx = EvaluationContext(
        key=user_id, 
        attributes={"plan": "pro"}
)
enabled = await engine.flag_client.get_boolean_value("new-checkout", False, ctx)

The dashboard has a full flag management UI to create, edit, enable/disable flags, manage targeting rules and segments, all without touching code. The CLI covers everything too for teams that prefer it.

What hasn't changed

The core idea is still the same: route lifecycle management via decorators, zero-restart control, and a dashboard your whole team can use. It still works as a standalone embedded library if that's all you need. The new stuff is additive.

Links

We're still actively building. If you ran into friction last time, I'd genuinely like to know whether any of this addresses it. And if you have things you'd still want drop them in the comments. The roadmap is still shaped more by what people actually need than what we think they need.

Thanks for the feedback last time. It pushed us in the right direction.


r/FastAPI • • Apr 03 '26

Question FastAPI ML Service on Railway — BackgroundTasks + SentenceTransformer 502, Pinecone never getting indexed

0 Upvotes

Building a RAG-based appliance manual assistant. Works perfectly on localhost, breaks in production on Railway.

Stack: FastAPI, Pinecone, SentenceTransformer, Groq, Cloudinary, MongoDB. Frontend on Vercel, backend + ml_service both on Railway as separate services.

The full failure chain I traced:

  • Cloudinary env vars incomplete (only URL set, no API key/secret) → manual PDFs never uploaded

  • No upload → no QR generated → nothing sent to ML service

  • ML service never indexed anything into Pinecone

  • RAG queries return empty every time

Cloudinary is fixed now. Still have these open questions:

Problem 1 — 502 on upload processing ML service was loading SentenceTransformer synchronously on the request thread, Railway proxy was timing out. Fixed by moving to a global singleton + asyncio.to_thread inside BackgroundTasks. Is this the right pattern for heavy CPU tasks in FastAPI prod or is there a better approach?

Problem 2 — Background task failures are silent If Pinecone is unreachable or OOM happens inside a BackgroundTask, MongoDB status stays "processing" forever. Currently wrapping everything in try/except and updating to "failed". Is there a better observability pattern here — some kind of task result tracking without bringing in Celery?

Problem 3 — Pinecone index object not JSON serializable Debug route was returning the Pinecone index object directly, got this:

TypeError("'_thread.RLock' object is not iterable")

Fixed by returning index.describe_index_stats().to_dict() instead. Posting in case it saves someone else time.

Main question: Is eager-loading SentenceTransformer in a FastAPI startup event via asyncio.to_thread the right call on Railway to avoid cold start 502s? Any memory gotchas on the 512MB starter plan when OCR + embeddings are running simultaneously?


r/FastAPI • • May 25 '26

pip package Ldcorn : A master proxy and process manager for path-based routing across Uvicorn worker pools.

Thumbnail
gallery
1 Upvotes

https://github.com/amzker/ldcorn

Ldcorn

Path-based routing/grouping and process management for Uvicorn worker pools.

Ldcorn lets you split your Uvicorn workers into groups and route requests to each group by URL path. all from a single Python config file, without splitting your app into separate services.

How it works

  [ Nginx / HAProxy / ... ]
      │
      ▼
  [ Ldcorn ]
      │
      ├── /ml-pipeline  ──►  WorkerGroup "ml"        [ Worker ml1 ]
      │
      ├── /ws, /counter ──►  WorkerGroup "websocket"  [ Worker wb1 ]
      │
      └── *             ──►  WorkerGroup "default"    [ Worker d1 ]
                                                      [ Worker d2 ]
                                                      [ Worker d3 ]

Each worker group runs as isolated OS processes. A request routed to ml will never touch a default worker, and vice versa.

Installation

pip install ldcorn
# or
uv add ldcorn

Quickstart

1. Create ldconfig.py

from ldcorn.config import LdConfig, WorkerGroup

# routes can be updated at runtime without restarting the process
config = LdConfig(
    bind="127.0.0.1:8000",
    workers=[
        WorkerGroup(
            name="default",
            app="main:app",
            instances=2,
            max_req_per_worker=0,  # 0 = unlimited
            routes=["*"],          # fallback for all unmatched routes
            reload_on_sighup=True,
            uvicorn_log_level="error",
            max_restarts_on_crash=3,
            restart_backoff_on_crash=2
        ),
        WorkerGroup(
            name="ml_heavy",
            app="main:app",        # does not need to be the same app
            instances=1,
            max_req_per_worker=100,
            routes=["/ml-pipeline"], 
            reload_on_sighup=False, # skip reloads of worker entirely.
            uvicorn_log_level="error",
            max_restarts_on_crash=3,
            restart_backoff_on_crash=2
        ),
        WorkerGroup(
            name="websocket_stateful",
            app="main:app",
            instances=1,
            max_req_per_worker=0,
            routes=["/ws", "/counter"], 
            reload_on_sighup=False,
            uvicorn_log_level="error",
            max_restarts_on_crash=3,
            restart_backoff_on_crash=2
        )
    ]
)

2. Run

ldcorn -c ldconfig.py

3. Reload on config or code change

kill -HUP <ldcorn_pid>

Ldcorn starts new workers, waits for them to be healthy, swaps the routing table, then lets old workers finish their active requests before exiting.

If you use systemd, set ExecReload to send SIGHUP and use systemctl reload ldcorn for deploys.

Is this for you?

Use Redis or a database for shared state. Ldcorn routes requests to worker groups. If you need shared counters, session data, or any state that survives a worker restart, use a proper store. Don't rely on in-process memory for anything that needs to be shared across machines or services. If it just needs to be consistent within a single process while your app is running, connection counters, rate tracking, WebSocket registries ,a dedicated single-instance worker group is sufficient and simpler.

Use microservices or container orchestration For most usecases, if you have resources and time then split into microservice. ldcorn gives you fine-grained control on a single machine. If you need to scale horizontally across machines, microservices and container orchestration is the right path.

If your entire app is synchronous and blocking, Ldcorn won't help. Process isolation contains the damage from blocking code. it doesn't fix it. If every endpoint blocks, every worker group will still saturate. The solution there is fixing the blocking code.

Use cases:

Ldcorn is effective when you need fine-grained control over how a single machine's workers are allocated and routed:

Resource allocation and priority tiering. Route /api/premium/* to a dedicated group of workers with no concurrency cap, while a separate group handles free-tier traffic with stricter limits. Each group is sized independently.

Asymmetric worker allocation. Heavy compute like ML inference might need 6 workers to stay responsive, while your fast I/O endpoints handle load fine with 2. With round-robin you scale everything uniformly. With Ldcorn you allocate exactly where it's needed.

Routing between different apps or codebases. Each worker group can run a completely different ASGI application . modern:app alongside legacy:app, for example. This lets you route traffic between codebases or gradually migrate individual API paths without setting up a separate reverse proxy.

Dynamic routing and config updates. Reroute a path, adjust concurrency limits, or scale a worker group up or down. Ldcorn applies these changes at the routing layer without restarting worker processes. Useful for runtime adjustments without a full deploy.

Features

Path routing with longest prefix match. Routes are matched by the longest matching prefix. Ties between equal-length prefixes resolve by definition order in your config.

Per-group concurrency limits. max_req_per_worker caps how many concurrent requests a single worker handles. Requests over the limit queue asynchronously and wait for a free slot, they don't spill into other groups.

Hot config updates without process restarts. Set reload_on_sighup=False on a group to exclude it from SIGHUP worker restarts. You can still update its routes, max_req_per_worker, or instances in the config. those changes apply at the routing layer immediately without touching the process.

Scaling without full restart. Increase instances from 1 to 4 on an opted-out group and Ldcorn keeps the existing process running and spawns the 3 additional ones.

Auto-restart on crash. Workers that crash are automatically restarted with configurable backoff (restart_backoff_on_crash).

Benchmarks

Both scenarios use the same setup:

  • Hardware: 16-core Intel Core i7-13620H

  • Database: MongoDB via motor (async)

  • Load: 100 concurrent connections on fast endpoints, 10 on heavy endpoints, 120s duration

  • Uvicorn: 6 workers, round-robin

  • Ldcorn: 6 workers total , 3 default, 1 ml, 1 math, 1 websocket

Scenario 1: Fully async, no blocking code

All endpoints use async drivers. CPU work is offloaded with asyncio.to_thread.

EndpointLdcorn GroupLdcorn (Req/s)Uvicorn (Req/s)Diff
Fast I/Odefault : 3 workers1,4381,699-15.3%
DB Readdefault : 3 workers152178-14.4%
DB Insertdefault : 3 workers149183-18.7%
DB Upsertdefault : 3 workers148184-19.6%
DB Deletedefault : 3 workers151181-16.5%
Math Primemath : 1 worker171173-1.3%
Heavy MLml : 1 worker5688-36.9%
Stateful Counterwebsocket : 1 worker201197+1.8%

The -15% on default endpoints is not Ldcorn overhead. it's because only 3 of the 6 workers are assigned to that group. The rest are occupied with their own routes. In a real mixed workload, that separation is the point. counter value stays consistent because all counter requests route to the same worker process.

When your app is fully async with no blocking code, round-robin Uvicorn is the better choice if you are aiming to improve performance via ldcorn.

Scenario 2: Mixed workload with blocking endpoints

time.sleep(random.uniform(1, 3)) added to the ML and Math handlers. This simulates a realistic mixed workload: some endpoints are well-optimized async, others are slow due to CPU-bound work, sync DB calls or third-party integrations that can't easily be made async.

EndpointLdcorn GroupLdcorn (Req/s)Uvicorn (Req/s)Diff
Fast I/Odefault : 3 workers95032+2,899%
DB Readdefault : 3 workers1013+2,972%
DB Insertdefault : 3 workers992+4,867%
DB Upsertdefault : 3 workers992+4,843%
DB Deletedefault : 3 workers1012+5,069%
Math Primemath : 1 worker0.521—
Heavy MLml : 1 worker0.501—
Stateful Counterwebsocket : 1 worker1334+3,362%

With blocking on the ML and Math handlers, Uvicorn's round-robin distributes those requests across all 6 workers. All 6 event loops freeze. Fast I/O drops to 32 req/s.

Ldcorn's ML and Math workers saturate the same way the blocking is still there, it's just contained. The default and websocket groups continue at full throughput with no awareness of what's happening in the other groups.

The time.sleep here is just a stand-in for anything that occupies a worker, a slow ML inference call, a CPU-bound computation, a third-party API with unpredictable latency, or even just a route that legitimately handles long-lived connections. The specific cause doesn't matter. What matters is that whatever is happening in one group stays in that group. The same isolation that protects fast I/O from a blocked ML worker is what lets you give premium users a dedicated pool, pin a WebSocket to a single process, or route two different codebases from one entry point. All for the same reason: requests to one group never affect workers in another.

All benchmarks are reproducible, see /examples.

Production notes

Memory during reloads. On SIGHUP, Ldcorn starts new workers before shutting down old ones. Both pools run simultaneously during the handover. If your workers load large ML models or heavy frameworks, make sure you have enough free memory or swap for the transient 2x spike.

Run behind a reverse proxy. Ldcorn does not inject X-Forwarded-For or X-Real-IP headers. Put Nginx (or HAProxy or Traefik) in front and configure it to set those headers so your workers see the correct client IPs.

Keep-Alive. Connections between the client and Ldcorn are closed after each request. This is intentional for hot-swap stability. For typical API traffic the overhead is negligible.

bind changes need a full restart. Changing the bind address does not take effect on SIGHUP , only on a full process restart.

TODO:

  • Alternative worker runtimes. Support for other worker types such as gevent.

  • Pre/Post hooks. Extensibility hooks for worker lifecycle and routing events.

  • Visibility and metrics. Internal metrics for monitoring request queues and worker health.

  • Queue wait timeouts / disconnect monitoring. Dropping abandoned requests from the concurrency queue if the client disconnects before a worker becomes available.


r/FastAPI • • Feb 23 '26

Other Your app can feel slow even if your APIs are fast. Here’s why.

Thumbnail
reddit.com
0 Upvotes

r/FastAPI • • Apr 30 '26

Tutorial What “production-ready FastAPI” actually means beyond making the route work

15 Upvotes

A lot of beginner FastAPI projects stop at:

u/app.post("/login")
def login():
    ...

But in real apps, “it works” is not the same as “it’s safe to ship.”

Some things I think every FastAPI route should be checked for:

  • Does the route verify the current user owns the resource?

  • Does it return only safe response fields?

  • Are expired / invalid tokens tested?

  • Are duplicate emails handled properly?

  • Are async DB sessions used correctly?

  • Are errors consistent and not leaking internals?

  • Are tests covering failure cases, not only happy paths?

The biggest jump for me was realizing that backend quality is mostly about edge cases.

Curious what other FastAPI devs here check before shipping a route?


r/FastAPI • • Jul 24 '25

Question I'm building an "API as a service" and want to know how to overcome some challenges.

6 Upvotes

Hey devs, I’m building an API service focused on scraping, and I’m running into a problem.

The main problem I'm facing is having to manually build the client-side ability to self-create/revoke API keys, expiration dates, and billing based on the number of API calls.

Is there a service focused on helping solve this problem? Do you know of anything similar?

Appreciate any recommendations!


r/FastAPI • • Nov 29 '23

feedback request An ultrafast framework for deploying ASGI apps to production

6 Upvotes

TL;DR: Deploy ASGI apps quickly onto pay-per-second cloud machines

I’m Eli, and my co-founder and I built Beam to run Python code on the cloud. Beam can be installed as a Python library, and it lets you add a decorator to your code, packages your app into a container, and runs it on the cloud.

Beam provides a Python SDK that lets you run your ASGI apps on the cloud without ever leaving your IDE. The only thing you need is to install our CLI, run beam deploy, and your app will provision itself onto the cloud. That’s it.

Here’s how you’d describe a FastAPI app:

from beam import App, Runtime, Image
from fastapi import FastAPI

# The environment your code will run on
beam_app = App(
    name="my-app",
    runtime=Runtime(
        image=Image(python_packages=["fastapi", "httpx"]),
    ),
)

# Define a FastAPI app
app = FastAPI()

# The request looks like: https://YOUR_APP_URL/?number=6
@app.get("/")
def multiply(number: int):
    return number * 4

# Entrypoint to the app. When deployed, this HTTP endpoint will be publicly exposed to the internet.
@beam_app.asgi(authorized=False)
def handler():
    return app

This FastAPI app can get deployed onto the cloud by running only one command:

beam deploy app.py

Beam includes bells-and-whistles for production, like load balancing, authentication, and usage metrics. It includes a 10 hour free trial, so you can try it out and see if you like it.

Things you can build with Beam

Pricing

Beam is serverless, so you'll only pay for the compute you've used, down to the second. For $0.10 cents an hour, you'll get an API that includes autoscaling, file storage, secrets management, versioned endpoints, and hot-reloading for test purposes.

Here are our quick links:

Website: https://beam.cloud

Github with example apps and tutorials: https://github.com/slai-labs/get-beam/tree/main/examples

Docs: https://docs.beam.cloud

We’d be happy if you gave this a try! Let me know what you think and if there’s anything you’d like us to build in the future.


r/FastAPI • • Mar 14 '26

feedback request I got tired of wasting 2 weeks on setup for every AI idea, so I built a FastAPI + Stripe Starter Kit.

0 Upvotes

Hey everyone,

Over the past few months, I've been trying to test a few AI SaaS ideas. The part that always slowed me down wasn't the core logic itself, but the repetitive backend setup. Wiring up JWT authentication, configuring Stripe webhooks, setting up the database, and integrating the OpenAI API always cost me weeks before I could even see if my idea had a pulse.

I figured other solo devs and indie hackers probably hate doing that "plumbing" phase too. So, I cleaned up my architecture, modularized it, and turned it into a production-ready template: FastAPI AI Starter Kit.

Here is what's working out of the box:

  • FastAPI Backend: Async by default, extremely fast and pythonic.

  • Authentication: JWT-based auth ready to use.

  • Payments: Stripe integration with pre-configured webhooks for subscriptions.

  • AI Ready: Base endpoints to connect with OpenAI/LLMs to start building your AI features immediately.

  • Clean Architecture: Structured for scalability (easy.env config, base CRUD endpoints).

The goal is simple: skip the 2-3 weeks of boring setup and start shipping your actual product on Day 1.

I priced it at a one-time fee of $29 to keep it highly accessible for fellow solo developers.

You can check it out here: manugutierres.gumroad.com/l/FastAPIAIStarterKit

I would love to get your feedback! What backend features do you feel are absolutely mandatory when you are starting a new project? Happy to answer any questions about the code structure or FastAPI in general.


r/FastAPI • • Sep 26 '25

Question Most commom folder structure

Post image
19 Upvotes

I'm a front-end dev learning Fastapi, can u guys show me a good folder structure?

I'm using fastapi standard install + sqlalchemy + psycopg + postgres

I have this inside my main folder, i think i need to create a service folder to do the db stuff right?


r/FastAPI • • May 02 '26

Other FastAPI gives you the spec. UIGen gives you the full React Frontend. Zero code. [Update]

16 Upvotes

Hey everyone - UIGen just got way easier to try (Faster AI assisted config and theming)

A few days ago I shared UIGen: a CLI tool that turns your OpenAPI spec into a full React frontend at runtime - no code generation, no build step. Update your FastAPI backend → restart the CLI → UI updates instantly. Your spec stays the source of truth.

What UIGen gives you out of the box

  • Auto CRUD views (list, detail, create, edit)

  • Full auth flows (login, signup, password reset)

  • File uploads, relationships, pagination, search

  • Data visualizations (new x-uigen-chart)

  • Production-ready React output you can extend/customize

The big new upgrade: AI-assisted setup

I added two AI skills that understand UIGen's architecture and do the heavy lifting:

1. Auto-Annotate Skill

Feeds your spec to your AI assistant (Cursor, Claude, etc.) and it automatically:

  • Detects & marks login/signup endpoints (x-uigen-login etc)

  • Finds relationships (users → posts, orders → customers)

  • Identifies file uploads

  • Spots good candidates for charts

2. Auto-Style Skill

Generates beautiful, production-ready CSS with simple prompts like:

"Make it look like Material Design" or "Dark theme with blue accents"

No manual CSS files or build processes - styles inject at runtime.

New super simple workflow

  1. @uigen-dev/cli init → bootstraps your project

  2. Let AI auto-annotate your spec (or use the visual config GUI)

  3. Let AI generate your theme

  4. Run npx @uigen-dev/cli serve yourspec.yaml and iterate

No frontend code to maintain.

Real example you can try right now

There's a full Meeting Minutes app in the repo (FastAPI + async SQLAlchemy + PostgreSQL + Alembic). ~2,000 lines of clean Python. Just clone, spin up the backend with Docker, and point UIGen at the auto-generated OpenAPI spec. Full CRUD, auth, file uploads, relationships — all working.

Current priorities for v1

  • Charting polish

  • Better layout options (without bloat)

  • App branding (name, icon, etc.)

  • Theme registry for instant beautiful starts

The goal

You focus on building a great API. UIGen + AI handles the frontend UI so you can ship faster.

Links

Happy to hear what you think


r/FastAPI • • Mar 09 '25

Question Iniciante no FastAPI, Duvida Sobre Mensagens do Pydantic

0 Upvotes

Resumo da dúvida

Estou a desenvolver uma API com FastAPI, no momento me surgiu um empecilho, o Pydantic retorna mensagens conforme um campo é invalidado, li e reli, todas as documentações de ambos FastAPI e Pydantic e não entendi/não encontrei, nada sobre modificar ou personalizar estes retornos. Alguém tem alguma dica para o iniciante de como proceder nas personalizações destes retornos ?

Exemplo de Schema utilizado no projeto:

class UserBase(BaseModel):
    model_config = ConfigDict(from_attributes=True, extra="ignore")

class UserCreate(UserBase):
    username: str
    email: EmailStr
    password: str

Exemplo de rota de registro:

@router.post("/users", response_model=Message, status_code=HTTPStatus.CREATED)
async def create_user(user: UserCreate, session: AsyncSession = Depends(get_session)):
    try:
        user_db = User(
            username=user.username,
            email=user.email,
            password=hash_password(user.password),
        )

        session.add(user_db)
        await session.commit()
        return Message(message="Usuário criado com sucesso")

    except Exception as e:
        await session.rollback()
        raise HTTPException(status_code=HTTPStatus.BAD_REQUEST, detail=str(e))

Exemplo de retorno ao passar um e-mail do tipo EmailStr inválido:

{
  "detail": [
    {
      "type": "value_error",
      "loc": ["path", "email"],
      "msg": "value is not a valid email address: An email address must have an @-sign.",
      "input": "test",
      "ctx": {
        "reason": "An email address must have an @-sign."
      }
    }
  ]
}

Exemplo de retorno simples que desejo

{
    "detail": "<campo x> informa é inválido"
}

r/FastAPI • • Jul 01 '26

Tutorial Handling Stripe webhooks in FastAPI

Thumbnail
highlit.co
4 Upvotes

A FastAPI endpoint that verifies Stripe's signature, then routes each event type to the right billing action.

Three takeaways

  1. Always verify a webhook's signature against a shared secret before trusting its contents.

  2. Read the raw request body for signature checks — parsed JSON won't match the signed bytes.

  3. Return 200 quickly and delegate the actual work so the provider considers the event delivered.


r/FastAPI • • Jan 16 '26

Question Anyone know about Meta closing down their B2B business globally?

Thumbnail reddit.com
0 Upvotes