r/FastAPI • • Dec 16 '22

Question Can the same graphql schema be used across multiple strawberry fastapi routers?

Thumbnail
stackoverflow.com
0 Upvotes

r/FastAPI • • Oct 05 '23

Question Order of response

0 Upvotes

I have created an fast api to get response from dynamodb (query).. now there are 20 key-value pairs that i am getting in each object of the response is there any way to make sure that which key value pair i want on top of each object


r/FastAPI • • Mar 15 '23

Question Using FastAPI with Flask

0 Upvotes

I'm stuck trying to properly initialize my project to run on uvicorn to use FastAPI and continue to build on the project I currently have (which is in Flask). The initializing code is below. Does anyone know how I can use FastAPI to build out the apis and use flask to build out my routes to display webpages? I'd like to not completely start over btw (I'd like to learn through this).
code is below

file name and location: website/app.py

from fastapi import FastAPI
from fastapi.middleware.wsgi import WSGIMiddleware
import uvicorn
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_migrate import Migrate


db = SQLAlchemy()
migrate = Migrate()
def create_app():
		api = FastAPI()
		app = Flask(__name__)
		api.mount("/", WSGIMiddleware(app))
		app.config['SECRET_KEY'] = 'abcdefg'
		app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///db.sqlite3'
		db.init_app(app)
		migrate.init_app(app, db)
	
		from .views import views
		from .auth import auth
		from .util import util
		from .admin import admin

		app.register_blueprint(views,url_prefix='/')
		app.register_blueprint(auth,url_prefix='/')
		app.register_blueprint(util,url_prefix='/')
		app.register_blueprint(admin,url_prefix='/admin')

		from .models import Form, User

		#create_database(app)

		login_manager = LoginManager()
		login_manager.login_view = 'auth.login'
		login_manager.init_app(app)

		@login_manager.user_loader
		def load_user(id):
				return User.query.get(int(id))


		return app

file name and location: main.py

from website.app import create_app
import uvicorn
web_app = create_app()

if __name__=="__main__":
		# run	flask	application
		web_app.run(debug=True, host="0.0.0.0", port=8080)

r/FastAPI • • Jan 12 '23

Hosting and deployment Binding application to specific IP not working.

0 Upvotes

We already have an application that runs on a specific IP address (e.g., 20.21.22.10, 20.21.22.11, 20.21.22.12). Now I'm creating another application but instead of running uvicorn on new address, I want to run it with 20.21.22.10 IP but using different port (8200).

I'm having an error while explicitly binding my app to an existing address that says:
```
[Errno 99] error while attempting to bind on address ('20.21.22.10', 8200): cannot assign requested address
```

How can I resolve this? I've already tried searching whether if it's from FastAPI or Uvicorn and I always stumbled upon across "root_path". After reading the documentation, it doesn't seem like it's a solution to my problem.


r/FastAPI • • Nov 20 '22

Other How & Why I Built My Very Own Music Player

0 Upvotes

Hello FastAPI community! 😀

So a few days ago I presented MonoBox here - a self-hosted music player I built 🎶

MonoBox's GitHub repo: MonoBox

Today I want to do something a little different - and present an article I wrote about the entire process I went through, the difficulties I encountered, and how I learned everything from scratch to build MonoBox. All of this in order to help other people who are also learning programming and might be struggling 👨‍💻

I would be absolutely grateful if you spare a few minutes to read what I wrote, and let me know what you thought (here or in the article itself) and in case you have not yet starred me on GitHub, shame on you I would greatly appreciate it if you could do so ⭐

Introducing MonoBox: How & Why I Built My Very Own Music Player

Another shorter piece that describes my process step-by-step and includes videos and coding milestones, which may provide additional or related ideas:

Build Your Own Spotify: Killer Programming Project Idea in React Native and FastAPI


r/FastAPI • • Aug 04 '20

serialization of sqlalchemy quer result

0 Upvotes

i have this query

def get_users(db: Session, skip: int = 0, limit: int = 100):
    return db.query(models.User).offset(skip).limit(limit).all()

and this model

class User(Base):
__tablename__ = "myusers"

id = Column(Integer, primary_key=True, unique=True, nullable=False) name = Column(String) password = Column(String) usertype = Column(Integer)

this is my endpoint

@app.get("/users/")
def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    users = crud.get_users(db, skip=skip, limit=limit)
    return BaseResponse(code=status.HTTP_200_OK, status=True, result=users)

and this is the base_response class

class BaseResponse(BaseModel):
status: bool = Field(True)
code: int
result: Optional[dict] = None
error: Optional[Error] = None

I am getting this error

validation error for BaseResponse result value is not a valid dict (type=type_error.dict)

I tried using marshmallow-sqlalchemy but still getting the same error


r/FastAPI • • Oct 18 '20

Jinja2 TemplateNotFound Error

0 Upvotes

I'm trying to access the "/" route however I keep on getting TemplateNotFound despite it being in the right directory.

main.py:

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
app = FastAPI()
from app.routers import home, auth
app.include_router(home.router)

home.py:

from fastapi import APIRouter, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

router = APIRouter()
router.mount("/app/static", StaticFiles(directory="app/static"), name="static")

templates = Jinja2Templates(directory="templates")

@router.get("/")
async def homepage(request: Request):
    return templates.TemplateResponse("home/index.html", {"request": request})

Directory Layout: https://i.imgur.com/qJjZTvs.png


r/FastAPI • • Dec 22 '23

Question Odd Rendering of OpenAPI Docs Schema's. Any solutions?

Post image
0 Upvotes

r/FastAPI • • Feb 17 '24

Question add additional models to openapi output which aren't used in fastapi endpoints for code generation purposes

0 Upvotes

I have an application where I use Pusher to send events to the front end and these events have a certain definition, I'd like fastapi to include these models in the openapi json so they can be included in the generated typescript api I use.

I know I could just dummy up some methods to get these generated, but I figured there might be a better way to tell fastapi to "include this entity in openapi output" without it having to be tied to a method or webhook definition?

The webhook functionality seems like it would be a decent workaround.


r/FastAPI • • Dec 22 '23

Question How is state preserved ?

0 Upvotes

Hey, I'm learning fastapi and I have a small doubt. Is state preserved during during browser sessions ?

Like, say I have a frontend website that calls my backend written in fastAPI.

VARIABLE = None

@app.get('/set/{v}')
def set(v): 
   VARIABLE = v

@app.get('/get')
def get(): 
   return VARIABLE

say, I first call 'localhost:8000/set/1' and the call 'localhost:8000/get', will I get 1 ?

And if someone else calls in the same order but with a different query parameter, will that be stored preserved as well?

I'm asking this cuz, I need to store oauth tokens to persist, between multiple different API calls, what would be a recommend way to do this?

any help is appreciated, thanks


r/FastAPI • • Feb 17 '24

Question How to get rid of authentication boilerplate

0 Upvotes

I am a beginner so there is probably something important that I am missing. I have this boilerplate a lot in my code:

@router.post("/{branch_name}", response_model= schemas.BranchResponseSchema, status_code=status.HTTP_201_CREATED)
def create_branch(user_name: str, repository_name : str, branch_name: str, 
                  db: Session = Depends(database.get_db), 
                  current_user = Depends(oauth2.get_current_user)):
   if current_user.name != user_name:
      raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, 
           detail="User does not have permission to create a branch for another user")

And I was wondering what the correct way to handle the cases where a user tries to change something he does not own.


r/FastAPI • • May 29 '24

Tutorial Implementing Firebase Cloud Storage In Your Python App — In Just a Few Steps.

Thumbnail
medium.com
4 Upvotes

r/FastAPI • • Jul 19 '24

Question [Help] Issues with POST Method for Sending Emails with/without Attachments

0 Upvotes

Hi everyone,

I'm currently developing an email sending API with FastAPI, which supports sending HTML emails and will soon handle attachments.

I'm facing some issues with the POST method, specifically when trying to incorporate the attachment functionality.

Here's what I've implemented so far:

  1. **API Setup**: Using FastAPI to handle requests.

  2. **Email Functionality**: Currently supports HTML content.

  3. **Future Plans**: Include file attachments.

**Problem**: I'm having trouble configuring the POST method to handle optional attachments properly. The method should work both when an attachment is included and when it's just a regular email without attachments. Interestingly, the method works perfectly when I remove the file parameter from the POST request, which means it fails only when trying to include an attachment.

**Current SchemaRequest**:

class EmailSchemaRequest(SQLModel):
    from_email: EmailStr = Field(..., 
description
="Email address of the sender")
    to_email: List[EmailStr] = Field(..., 
description
="Email address of the recipient")
    to_cc_email: Optional[List[EmailStr]] = Field(None, 
nullable
=True, 
description
="Email address to be included in the CC field")
    to_cco_email: Optional[List[EmailStr]] = Field(None, 
nullable
=True, 
description
="Email address to be included in the BCC field")
    subject: str = Field(..., 
description
="Subject of the email", 
min_length
=1, 
max_length
=50)
    html_body: str = Field(..., 
description
="HTML content of the email", 
min_length
=3)

**Current post method**:

u/router.post("/", 
status_code
=status.HTTP_202_ACCEPTED, 
response_description
="Email scheduled for sending")
def schedule_mail(
    
background_tasks
: BackgroundTasks,
    
request
: EmailSchemaRequest,
    
file
: UploadFile | bytes = File(None),
    
session
: Session = Depends(get_session), 
    
current_user
: UserModel = Depends(get_current_active_user)
):
    email = EmailModel(
        
from_email
=normalize_email(
request
.from_email),
        
to_email
=normalize_email(
request
.to_email),
        
to_cc_email
=normalize_email(
request
.to_cc_email),
        
to_cco_email
=normalize_email(
request
.to_cco_email),
        
subject
=
request
.subject.strip(),
        
html_body
=
request
.html_body,
        
status
=EmailStatus.PENDING,
        
owner_id
=
current_user
.id
    )

    if 
file
:
        validate_file(
file
)
        try:
            service_dir = os.path.join(PUBLIC_FOLDER, 
current_user
.service_name)
            os.makedirs(service_dir, 
exist_ok
=True)
            file_path = os.path.join(service_dir, 
file
.filename)
            with open(file_path, "wb") as f:
                f.write(
file
.file.read())
            email.attachment = file_path
        except Exception as e:
            logger.error(f"Error saving attachment: {e}")
            raise HTTPException(
status_code
=status.HTTP_500_INTERNAL_SERVER_ERROR, 
detail
="Failed to save attachment")

    email = create_email(
session
, email)
    
background_tasks
.add_task(send_email_task, email.id, email.owner_id)
    return {"id": email.id, "message": "Email scheduled for sending"}

Any guidance or resources would be greatly appreciated. Thank you!

NewMethod:

@router.post("/", 
status_code
=status.HTTP_202_ACCEPTED, 
response_description
="Email scheduled for sending")
async def schedule_mail(
    
background_tasks
: BackgroundTasks,
    
payload
: str = Form(..., 
description
="JSON payload containing the email details"),
    
file
: UploadFile = File(None, 
description
="Optional file to be attached"),
    
session
: Session = Depends(get_session), 
    
current_user
: UserModel = Depends(get_current_active_user)
):
    try:
        
# Check if the payload is a valid JSON
        email_request = EmailSchemaRequest.model_validate_json(
payload
)
        
# Create the email object with the data from the request validated
        email = EmailModel(
            
from_email
=normalize_email(email_request.from_email),
            
to_email
=normalize_email(email_request.to_email),
            
to_cc_email
=normalize_email(email_request.to_cc_email),
            
to_cco_email
=normalize_email(email_request.to_cco_email),
            
subject
=email_request.subject.strip(),
            
html_body
=email_request.html_body,
            
status
=EmailStatus.PENDING,
            
owner_id
=
current_user
.id
        )
        
# Save the attachment if it exists
        if 
file
:
            file_path = await save_attachment(
file
, 
current_user
)
            if file_path is None:
                raise HTTPException(
status_code
=status.HTTP_500_INTERNAL_SERVER_ERROR, 
detail
="Failed to save attachment")
            email.attachment = file_path

        
# Create the email in the database
        email = create_email(
session
, email)
        
# Schedule the email for sending
        await 
background_tasks
.add_task(send_email_task, email.id, email.owner_id)
        
# Return the response with the email id and a message
        return {"id": email.id, "message": "Email scheduled for sending"}
    except json.JSONDecodeError:
        return {"error": "Invalid JSON format", "status_code": 400}
    except ValueError as e:
        return {"error": str(e), "status_code": 400}

r/FastAPI • • Aug 08 '24

Question Fastapi + Gunicorn HUP signal to reload workers

0 Upvotes

Hello, I have a very simple fast api server running for one endpoint, it has a systemctl to start the server using gunicorn.

I also have a script in my computer that deploys new code to the server and sends a HUP signal to Gunicorn (so they finish whatever they are doing and reload workers with new code). The thing is that if I do this on the fly while the workers are running the old code, sometimes during this reload I get some fail requests and sometimes it does the reload gracefully without any problem. Is there a way that I don't have fails at all?


r/FastAPI • • Oct 24 '24

Question How to stop an API while it's running?

4 Upvotes

How do I cancel an api call while it is functioning in backend?


r/FastAPI • • Mar 31 '25

Question how to add hubspot authentification option to a fastApi web app

0 Upvotes

i need help to add the possibility to users to login with hubspot in my fastApi web app , (im working with hubspot business plan)


r/FastAPI • • May 30 '26

Tutorial Made the best vibe coding template with FastAPI + NextJS+Alembic

Thumbnail
reddit.com
0 Upvotes

r/FastAPI • • Jun 18 '25

Hosting and deployment Flux API just dropped on RapidAPI! Free tier + $5 plans w/ 10K requests/day

0 Upvotes

🚀 Heads up devs: Flux API is now live on RapidAPI!

Plans:

  • Basic: FREE (10 requests/day)
    → Flux V only (unofficial)

  • Pro ($3/mo): 3K reqs/Month → Text-to-Video, Flux v2, Flux schnell ✅

  • Ultra ($5/mo): 10K reqs/day
    → Adds AI Translate + DeepSeek R1 / Llama 3.3 Turbo ✅

  • Mega ($7/mo): 24.4K reqs/day
    → All features + extra capacity

No rate limits on paid tiers.

👉 Link: Flux API on RapidAPI


Why this works:

  • Short & punchy: Highlights key numbers (free, 10K/day, $5).

  • Feature-focused: Uses ✅ to show upgrades between tiers.

  • Actionable: Clear link + audience targeting ("devs").

  • Flows well: Starts free → scales to advanced features.


r/FastAPI • • Sep 28 '25

Tutorial user auth in azure table storage using python and fastapi

Thumbnail reddit.com
0 Upvotes

r/FastAPI • • Mar 11 '21

Question Not getting exception traceback

0 Upvotes

In am trying to learn fastapi, I am creating a basic app using fastapi,sqlalchemy,alembic. But whenever there is a problem I am using :

try:
   suspected_line_with_problem
except Exception as e:
   print(e)

but this is very much time consuming and I am sure this is not the right way to debug errors. I have also tried these lines to log the errors:

#in main.py

log = logging.getLogger("uvicorn")
log.setLevel(logging.DEBUG)
command_line_handler = logging.StreamHandler()
command_line_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(levelname)s- api - %(asctime)s - %(message)s')
command_line_handler.setFormatter(formatter)
log.addHandler(command_line_handler)

Still I am not getting trackback or source of error, I have tried to start uvicorn with parameter --reload --log-level debug but still I am not seeing any traceback/helpful message, All I am getting is:

←[32mINFO←[0m:     127.0.0.1:62571 - "GET /blog/id/?num=4 HTTP/1.1" 500

Please guide.


r/FastAPI • • Apr 17 '26

feedback request Look for feedback on my fastapi project

4 Upvotes

Hi everyone,

I’d really appreciate it if you could take a look at my code and give me some feedback. The functionality is fairly basic and not the main focus here — what I’m really interested in is evaluating the structure, organization, and overall code quality. I’m trying to improve my understanding of best practices, so any suggestions in that direction would be especially helpful. Feel free to point out anything that could be improved, whether it’s readability, naming conventions, modularity, or general design choices.

Github: https://github.com/Petr201317/fastAPI_cinema

Thanks in advance for your time


r/FastAPI • • Mar 22 '26

Tutorial Vibeops FastAPI template

0 Upvotes

Been using Claude Code heavily and kept running into the same problem: every new session, the agent forgets your conventions, reinvents patterns, makes the same mistakes.

The fix I landed on: a structured AGENTS.md file that acts as a persistent constitution for your agent. Not just a README — it covers architecture decisions, hard constraints, coding conventions, and a Feature Kickoff Protocol that forces design-before-code on every new feature.

The protocol looks like this:

You say: "New feature: user registration and JWT auth"

Claude responds: "Entering design mode. No code yet." → produces a spec + Gherkin scenarios → waits for your approval → only then writes code.

I packaged this into a FastAPI template as a reference implementation:
👉

The AGENTS.md is the actual product. Everything else is just showing it in context.

Curious if others have landed on similar patterns — or what's broken for you with long Claude Code sessions.

FastAPi template: https://github.com/vibeops-central/fastapi-vibeops-template


r/FastAPI • • 20d ago

Tutorial FastAPI Cloud is now generally available ⚡

Thumbnail
medium.com
4 Upvotes

FastAPI Cloud is out of beta, so I tried deploying a small app with the CLI. I put together a walkthrough for anyone who wants to try it. It covers the first deploy, including the prompts you’ll see and how to check that the app is running.

If you’ve tried FastAPI Cloud, I’m curious how it compares with your usual deployment setup.


r/FastAPI • • May 16 '26

Question PyCharm 2026.1.2 + FastAPI hot reload broken?

4 Upvotes

I just installed the latest Pycharm today from some hype.

Apparently when I start my Fastapi app in debug mode using the Fastapi debug profile with uvicorn —reload parameter and I make any change the reload is triggered, the main process is killed and no new app instance is started. It just dies… I need to start my app again.

I don’t have this issue with VSCode, is there a workaround for it ?

I am using Python 3.14 with latest Fastapi, Gunicorn etc.