Skip to content

Instantly share code, notes, and snippets.

@raveenb
Last active September 18, 2023 06:32
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save raveenb/c0001484a79214c21785227d0688f57f to your computer and use it in GitHub Desktop.
Save raveenb/c0001484a79214c21785227d0688f57f 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
@ChenZ1186
Copy link

ChenZ1186 commented Apr 22, 2022

it works! thank you !
can you explain the rule of each raw, such as :

ngrok_tunnel = ngrok.connect(8000)
ngrok_tunnel - most important to understand !

nest_asyncio.apply()
uvicorn.run(app, port=8000)

can one specify all the imports at the top or it has to be written as you did?

thanks in advance!

@raveenb
Copy link
Author

raveenb commented Apr 22, 2022

i think ngrok can start earlier than fastapi
you can do all the imports at the top as well, dont see an issue with that

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment