Skip to content

Instantly share code, notes, and snippets.

Last active June 28, 2023 18:24
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
[FastAPI Single File Demo] Example fastapi single file testable example #fastapi
#!/usr/bin/env python3.7
import logging
import uvicorn
from fastapi import FastAPI
from starlette.responses import RedirectResponse
from starlette.testclient import TestClient
log = logging.getLogger(__name__)
app = FastAPI()
def read_main():
return {"message": "Hello World from main app"}
def test_slash(check: str):
"""Test if forward slash can be captured
return {"message": check}
subapi = FastAPI(openapi_prefix="/subapi")
async def read_sub():
return {"message": "Hello World from sub API"}
async def redirect():
url = app.url_path_for("redirected")
response = RedirectResponse(url=url)
return response
async def redirected():
return {"message": "you've been redirected"}
app.mount("/subapi", subapi)
client = TestClient(app)
def test_redirect_subapi():
url = app.url_path_for("redirect")
response = client.get(url)
assert response.json() == {"message": "you've been redirected"}
if __name__ == "__main__":"fastapi_test:app", host="", port=5000, log_level="info")
# From:
# The following works with the pycharm debugger with reload running in a docker-compose remote interpreter
from fastapi import FastAPI
import uvicorn
app = FastAPI()
def root():
a = "a"
b = "b" + a
return {"hello world": b}
if __name__ == '__main__':"main:app", host='', port=8000, reload=True)
# Notice the it's "main:app" and not app otherwise you get an error:
# WARNING: You must pass the application as an import string to enable 'reload' or 'workers'.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment