Search code examples
pythongoogle-colaboratoryfastapiuvicorn

How to run FastAPI / Uvicorn in Google Colab?


I am trying to run a "local" web app on Google Colab using FastAPI / Uvicorn like some of the Flask app sample code I've seen but cannot get it to work. Has anyone been able to do this? Appreciate it.

Installed FastAPI & Uvicorn successfully

!pip install FastAPI -q
!pip install uvicorn -q

Sample app

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}

Run attempts

#attempt 1
if __name__ == "__main__":
    uvicorn.run("/content/fastapi_002:app", host="127.0.0.1", port=5000, log_level="info")

#attempt 2
#uvicorn main:app --reload
!uvicorn "/content/fastapi_001.ipynb:app" --reload

Solution

  • You can use ngrok to export a port as an external url. Basically, ngrok takes something available/hosted on your localhost and exposes it to the internet with a temporary public URL.

    First install the dependencies

    !pip install fastapi nest-asyncio pyngrok uvicorn
    

    Create your app

    from fastapi import FastAPI
    from fastapi.middleware.cors import CORSMiddleware
    
    app = FastAPI()
    
    app.add_middleware(
        CORSMiddleware,
        allow_origins=['*'],
        allow_credentials=True,
        allow_methods=['*'],
        allow_headers=['*'],
    )
    
    @app.get('/')
    async def root():
        return {'hello': 'world'}
    

    Then run it down.

    import nest_asyncio
    from pyngrok import ngrok
    import uvicorn
    
    ngrok_tunnel = ngrok.connect(8000)
    print('Public URL:', ngrok_tunnel.public_url)
    nest_asyncio.apply()
    uvicorn.run(app, port=8000)