Running Flask / FastAPI app on Google Colab for Data Science and Machine Learning.

Posted by

How to serve Flask / FastAPI app in Google Colab

How to serve Flask / FastAPI app in Google Colab

If you are working on a data science or machine learning project in Google Colab and you want to serve a Flask or FastAPI app, here is a simple guide on how to do it:

Using Flask:

First, you need to install Flask in your Google Colab environment. You can do this by running the following command in a code cell:

!pip install flask

Then, you can create a Flask app and run it by using the following code:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run()

Now you can access your Flask app by clicking on the link provided in the output of the cell where you ran the app.

Using FastAPI:

For FastAPI, you need to install it in your Google Colab environment by running the following command in a code cell:

!pip install fastapi uvicorn

Then you can create a FastAPI app and run it by using the following code:

from fastapi import FastAPI

app = FastAPI()

@app.get('/')
def read_root():
    return {'Hello': 'World'}

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, port=8000)

Now you can access your FastAPI app by clicking on the link provided in the output of the cell where you ran the app.

By following these simple steps, you can serve Flask or FastAPI apps in Google Colab for your data science or machine learning projects.