I know that it's possible to mount an instance of flask on top of FastAPI. This means that all requests going to the root URL are handled by FastAPI and only the requests to the specified flask URL are forwarded to it. Is it possible to do this the other way around? I have a website that I've built with flask and I'd like to add an API to it to manage the database from another app. FastAPI has automatic documentation and validation which makes life a lot easier. The reason I want to mount it this way round
If not, can I host it separately with uvicorn and forward all URLs starting with /api/ to it and somehow return whatever it returns through flask?
The reason I'm mixing things up here rather than running them separately is that I'm having trouble accessing the database from outside of the flask application.
CodePudding user response:
I've done this with two separate Flask applications (see here).
It may work with a FastAPI instance.
CodePudding user response:
After some tinkering, I figured out a solution.
I am now running flask and FastAPI as two separate applications. I have added a route to flask that makes it act like a proxy for the FastAPI app:
API_URL = "http://127.0.0.1:8000/"
@views.route("/api/<path:rest>")
def api_redirect(rest):
return requests.get(f"{API_URL}{rest}").content
I then ran FastAPI with uvicorn main:app --root-path api/
so that the frontend knows where to find the openapi.json
file.
I solved the issue I was having with accessing the database (due to not being in a session) by adding the following code.
engine = create_engine(DB_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
models.db.metadata.create_all(bind=engine)
app = FastAPI()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/all-items", response_model=List[schemas.Item], tags=["items"])
def all_items(db: Session = Depends(get_db)):
return db.query(models.Item).all()
This creates a new session for each API call and then closes it when the call has been made.