Skip to content

Instantly share code, notes, and snippets.

@CareTiger
Forked from raveenb/fastapi_inside_jupyter.md
Created September 18, 2023 06:32
Show Gist options
  • Select an option

  • Save CareTiger/2f23e4b878e240b09a0a1fbfed09ccfb to your computer and use it in GitHub Desktop.

Select an option

Save CareTiger/2f23e4b878e240b09a0a1fbfed09ccfb to your computer and use it in GitHub Desktop.
Run FastAPI inside Jupyter

How to Run FastAPI inside Jupyter

  • Ensure you have these installed and accessible from the notebook pyngrok, nest_asyncio, fastapi, uvicorn and other libs you want
%pip install pyngrok nest_asyncio fastapi uvicorn loguru
  • Create a FastAPI app
from fastapi import FastAPI
from pydantic import BaseModel
from loguru import logger

app = FastAPI()

class UserRequestIn(BaseModel):
    text: str
    
@app.post("/test")
def index(request: UserRequestIn):
    logger.debug(request)
    return {"ok": True}
  • Start ngrok tunnel
import nest_asyncio
from pyngrok import ngrok
import uvicorn

ngrok_tunnel = ngrok.connect(8000)

ngrok_tunnel
  • Patch Event Loop and start server
nest_asyncio.apply()
uvicorn.run(app, port=8000)
  • Click on the ngrok url, and visit /docs and you will have the Swagger/OpenAPI page and call your api's from there
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment