Skip to content

Instantly share code, notes, and snippets.

@wshayes
Last active June 28, 2023 18:24
Show Gist options
  • Save wshayes/f0ae5cfa65c87dc2e9092d6c634d2912 to your computer and use it in GitHub Desktop.
Save wshayes/f0ae5cfa65c87dc2e9092d6c634d2912 to your computer and use it in GitHub Desktop.
[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__)
log.setLevel(logging.DEBUG)
app = FastAPI()
@app.get("/")
def read_main():
return {"message": "Hello World from main app"}
@app.get("/test/{check:path}")
def test_slash(check: str):
"""Test if forward slash can be captured
https://fastapi.tiangolo.com/tutorial/path-params/#path-convertor
"""
return {"message": check}
subapi = FastAPI(openapi_prefix="/subapi")
@subapi.get("/sub")
async def read_sub():
return {"message": "Hello World from sub API"}
@subapi.get("/redirect")
async def redirect():
url = app.url_path_for("redirected")
response = RedirectResponse(url=url)
return response
@subapi.get("/redirected")
async def redirected():
log.debug("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__":
uvicorn.run("fastapi_test:app", host="127.0.0.1", port=5000, log_level="info")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment