Building a simple FastAPI application
Finally, we can now get to our first FastAPI project. Our aim in this section is to introduce FastAPI by building a simple application. We shall cover in-depth operations in subsequent chapters.
We’ll begin by installing the dependencies required for our application in the todos
folder we created earlier. The dependencies are the following:
fastapi
: The framework on which we’ll build our application.uvicorn
: An Asynchronous Server Gateway Interface module to run our application.
First, activate your development environment by running the following command in your project directory:
$ source venv/bin/activate
Then, install the dependencies as follows:
(venv)$ pip install fastapi uvicorn
For now, we’ll create a new api.py
file and create a new instance of FastAPI as follows:
from fastapi import FastAPI app = FastAPI()
By instantiating FastAPI in the app variable, we can proceed to create routes. Let’s create a welcome route.
A route is created by first defining a decorator to indicate the type of operation, followed by a function containing the operation to be carried out when this route is invoked. In the following example, we’ll create a "/"
route that only accepts GET
requests and returns a welcome message when visited:
@app.get("/") async def welcome() -> dict: return { "message": "Hello World"}
The next step is to start our application using uvicorn
. In your terminal, run the following command:
(venv)$ uvicorn api:app --port 8000 --reload
In the preceding command, uvicorn
takes the following arguments:
file:instance
: The file containing the instance of FastAPI and the name variable holding the FastAPI instance.--port PORT
: The port the application will be served on.--reload
: An optional argument included to restart the application on every file change.
The command returns the following output:
(venv) ➜ todos uvicorn api:app --port 8080 --reload INFO: Will watch for changes in these directories: ['/Users/youngestdev/Documents/todos'] INFO: Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit) INFO: Started reloader process [3982] using statreload INFO: Started server process [3984] INFO: Waiting for application startup. INFO: Application startup complete.
The next step is to test the application by sending a GET
request to the API. In a new terminal, send a GET
request using curl
as follows:
$ curl http://0.0.0.0:8080/
The response from the application logged in your console will be the following:
{"message":"Hello World"}