Building a FastAPI Application and Deploying it with Vercel
Tags: python, vercel, fastapi, api
Published: 2023-06-23 09:23:59

Are you looking to build a powerful API using FastAPI and deploy it quickly? Look no further! In this tutorial, we'll walk through the steps of creating a FastAPI application and deploying it using Vercel.

### Setting up the Environment

To get started, make sure you have Python installed on your machine. We'll be using a virtual environment to keep our project dependencies isolated. Open your terminal and run the following command to create a virtual environment named `env`:

```bash
python -m venv env
```

Next, activate the virtual environment by running the following command:

```bash
source env/bin/activate
```

### Installing FastAPI and Uvicorn

Now that our virtual environment is activated, let's install the necessary dependencies. Run the following command to install FastAPI and Uvicorn:

```bash
pip install fastapi uvicorn
```

FastAPI is the web framework we'll be using to build our API, while Uvicorn is an ASGI server that will serve our FastAPI application.

### Creating the FastAPI Application

In your project directory, create a file called `main.py` and add the following code:

```python
import uvicorn
from fastapi import FastAPI

app = FastAPI()

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

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
```

This code sets up a basic FastAPI application with a single endpoint at the root URL ("/") that returns a JSON response with a "message" key.

### Running the FastAPI Application Locally

To run the FastAPI application locally, open your terminal and navigate to the project directory. Run the following command:

```bash
python main.py
```

This will start the Uvicorn server, and you should see output indicating that the server is running.

Now, open your web browser and visit [http://localhost:8000/](http://localhost:8000/). You should see the following JSON response:

```json
{
    "message": "Hello from FastAPI!"
}
```

Congratulations! You have successfully built and run a FastAPI application locally.

### Deploying the FastAPI Application with Vercel

To deploy our FastAPI application using Vercel, we need to create a `vercel.json` configuration file. Create a new file named `vercel.json` in your project directory and add the following content:

```json
{
  "version": 2,
  "builds": [
    { "src": "main.py", "use": "@vercel/python" }
  ],
  "routes": [
    { "src": "/(.*)", "dest": "/main.py" }
  ],
  "env": {
    "APP_MODULE": "main:app"
  }
}
```

In this configuration file, we specify that the source file for our deployment is `main.py`, and we use the `@vercel/python` builder. We also define a route that redirects all requests to `main.py`, and we set the `APP_MODULE` environment variable to `main:app`, which tells Vercel where to find the FastAPI application instance.

Next, we need to create a `requirements.txt` file that lists the project dependencies. Run the following command in your terminal to generate the `requirements.txt` file:

```bash
pip freeze > requirements.txt
```

This command will capture all the installed dependencies and their versions in the `requirements.txt` file.

### Setting up Git and Pushing the Code

Before deploying to Vercel, let's set up a Git repository and push our code to it. First, create a repository on GitHub or any other Git hosting platform. Once you have created the repository, navigate to your project directory in the terminal and run the following commands:

```bash
git init
git add .
git commit -m "Deploy FastAPI to Vercel"
git branch -M main
git remote add origin https://github.com/your-username/your-repo.git
git push -u origin main
```

Make sure to replace `your-username` and `your-repo` with your actual GitHub username and repository name.

### Deploying with Vercel

Now it's time to deploy our FastAPI application using Vercel. Open the Vercel website ([https://vercel.com](https://vercel.com)) and create a new project. Select your Git repository and configure the project settings as seen in the images.

![Vercel New Project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jq9sbd6p2uorro1bz9y0.png)

![Vercel Project Settings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yhge4ero47vrtkvmok2r.png)

After configuring the project, Vercel will automatically build and deploy your FastAPI application. Once the deployment is complete, you will receive a URL where your API is live!

Congratulations! You have successfully deployed your FastAPI application using Vercel. You can find the deployed code on [GitHub](https://github.com/mihaiandrei97/fastapi-vercel-tutorial) and access the live API [here](https://fastapi-vercel-tutorial.vercel.app/).

I hope this tutorial has been helpful in guiding you through the process of building a FastAPI application and deploying it with Vercel. Now you can take advantage of the power and speed of FastAPI, combined with the ease of deployment provided by Vercel, to create and deploy robust APIs in no time. Happy coding!