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
  • Save CareTiger/2f23e4b878e240b09a0a1fbfed09ccfb to your computer and use it in GitHub Desktop.
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
from pyngrok import ngrok

ngrok_tunnel = ngrok.connect(8000)

ngrok_tunnel
  • Patch Event Loop and start server
import nest_asyncio
import uvicorn

nest_asyncio.apply()
uvicorn.run(app, port=8000)
  • Click on the ngrok url printed above, and visit /docs endpoint and you will have the familiar Swagger 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