Deploy FastAPI on Google Colab: A Quick and Easy Guide

Are you looking to develop a FastAPI application directly in Google Colab? This tutorial will walk you through setting up and running FastAPI with localtunnel for exposing the app to the web.
Step 1: Install FastAPI and Uvicorn
To get started, install the required libraries. Use the following commands to install FastAPI and Uvicorn in your Colab environment:

!pip install "fastapi[standard]"
!pip install uvicorn
Step 2: Create a Simple FastAPI App
Next, let’s create a file called main.py
that contains a basic FastAPI application with two routes: one that returns a "Hello World" message and another that greets users by name.

%%writefile main.py
from fastapi import FastAPI
# Create FastAPI app
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.get("/hello/{name}")
async def say_hello(name: str):
return {"message": f"Hello {name}"}
Step 3: Run the FastAPI Application
To run the FastAPI app in Colab, use Uvicorn, which is an ASGI server for FastAPI.
You can run the app using the following command. We also use localtunnel to expose the app to the internet so you can access it externally.

!uvicorn main:app & npx localtunnel --port 8000 --subdomain fastapi & wget -q -O - https://loca.lt/mytunnelpassword
uvicorn main:app &
runs the FastAPI app in the background.npx localtunnel --port 8000 --subdomain fastapi
opens the FastAPI server to the internet via localtunnel on port 8000 and allows you to choose the custom subdomainfastapi
.wget -q -O -
ensures localtunnel runs seamlessly.
After executing the above, you should see a public URL that you can use to access your FastAPI app online.
Step 4: Test Your API
Once your app is up and running, you can use the public URL provided by localtunnel to test your API.
- To access the root endpoint, go to:
https://fastapi.loca.lt/
- To access the personalized greeting endpoint, try:
https://fastapi.loca.lt/hello/YourName
Run https://fastapi.loca.lt/docs

Run PostMan

That’s it! You’ve successfully set up FastAPI on Google Colab with a public URL for access. Now you can start building and testing FastAPI apps directly from your browser.