Introduction

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.8+ based on standard Python type hints.

Prerequisites

  • a UNIX-like system (see WSL if you are using Windows), in order to use the Valyent CLI
  • a Valyent account, with a registered payment method (you can sign up here)
  • Python3 and installed on your machine

Installing the CLI

curl -L https://cli.valyent.cloud/install.sh | sh

You can inspect the installation script here and the GitHub repository.

Authenticating

valyent auth login

Initializing the project

In the first place, we are going to install FastAPI dependencies. You can refer to the official documentation for more information.

pip install fastapi
pip install uvicorn[standard]

Then, we can scaffold a new FastAPI project :

mkdir -p fastapi-testing/app && cd fastapi-testing && touch app/main.py

Make sure to create a requirements.txt file, in order to install the dependencies in the Docker image :

touch requirements.txt

For this example, we are going to use the following dependencies :

# requirements.txt
fastapi>=0.68.0,<0.69.0
pydantic>=1.8.0,<2.0.0
uvicorn>=0.15.0,<0.16.0

In the app/main.py file, we can add the following code :

# app/main.py
from fastapi import FastAPI

app = FastAPI()

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

Now, we can initialize the valyent.toml configuration file, that allows to link the local codebase, to a Valyent application :

valyent init

This command will ask you to select/create a project and an associated application.

Adding the Dockerfile

Let’s add a Dockerfile so that Valyent can build a Docker image for your application.

touch Dockerfile

We can fill it with the following Dockerfile (coming from here) :

FROM python:3.9

WORKDIR /code

COPY ./requirements.txt /code/requirements.txt

RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt

COPY ./app /code/app

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]

Deploy the project

Valyent makes use of the PORT environment variable to determine which port to expose. We can set it with the following command :

valyent env set PORT=80

Then, we can deploy the application :

valyent deploy

Once the deployment is finished, type :

valyent open

to test your FastAPI application in your browser.