Developing the Tutorial Server#

Fast API First Steps#

First we develop a FastAPI* application such that it can run and be tested locally.

Note

In this tutorial commands are written for a Unix-like operating system. If you are using Windows* OS, you may need to adjust the commands accordingly.

Ensure Python* programming language is installed on your PC and create a new directory for the project.

mkdir tutorial-server
cd tutorial-server

Create a virtual environment and activate it.

python3 --version
python3 -m venv venv
echo "venv" >> .gitignore
source venv/bin/activate
pip install --upgrade pip

Create a requirements file and install the required packages.

echo "fastapi[standard]~=0.115.12" > requirements.txt
echo "uvicorn~=0.34.0" >> requirements.txt
pip install -r requirements.txt

Note

You should see output showing the packages being installed. If you got an error along the way it is possible the version of Python you are using is not compatible with the versions of the packages. These versions in the requirements file are known to work with Python 3.13 release. You might have multiple versions of Python installed on your computer - check with the command: which -a python3. If you have multiple versions, you can specify the version explicitly when creating the virtual env (venv) above.

Following Fast API First Steps document, copy the following code into a file named main.py in the project directory.

1#!/usr/bin/python3
2
3from fastapi import FastAPI
4
5app = FastAPI()
6
7@app.get("/")
8async def read_root():
9    return {"message": "Hello World"}

Note

Ensure the code is indented correctly because Python programming is sensitive to indentation.

And run the program locally with the following command

fastapi dev main.py

In another terminal, run the following command to test the application

curl localhost:8000

and it should reply with:

{"message":"Hello World"}

Additions to the FastAPI Application#

Now that we have the basics in place we want to add our code to perform the functions related to the counter.

Update the main.py file with the following code:

 1#!/usr/bin/python3
 2
 3from fastapi import FastAPI
 4from fastapi.middleware.cors import CORSMiddleware
 5from pydantic import BaseModel
 6import os
 7
 8origins = [
 9    "http://localhost:3000",
10]
11
12app = FastAPI()
13
14"""Necessary to allow CORS (Cross-Origin Resource Sharing) for the web UI"""
15app.add_middleware(
16    CORSMiddleware,
17    allow_origins=origins,
18    allow_credentials=True,
19    allow_methods=["GET, POST"],
20    allow_headers=["*"],
21)
22
23class Counter(BaseModel):
24    count: int
25
26initial_value = int(os.environ.get('INITIAL_COUNT', '0'))
27counter = Counter(count=initial_value)
28
29@app.get("/")
30async def read_root():
31    """Return a greeting message based on the environment variable TUTORIAL_GREETING"""
32    tutorial_greeting = os.environ.get('TUTORIAL_GREETING', 'Hello World')
33    return {"message": tutorial_greeting}
34
35@app.get("/counter")
36async def read_counter():
37    """Return the current count"""
38    return counter
39
40@app.post("/increment")
41async def increment_counter():
42    """Increase the counter by 1 and return it"""
43    counter.count += 1
44    return counter
45
46@app.post("/decrement")
47async def decrement_counter():
48    """Decrease the counter by 1 and return it"""
49    counter.count -= 1
50    return counter
51
52@app.post("/reinitialize")
53async def reinitialize_counter():
54    """Reinitialize the counter to the initial value and return it"""
55    counter.count = initial_value
56    return counter

Note

That’s it - the server is now complete. This uses a simple counter in memory to maintain the count. In a real application this would require a database or other persistent storage, and would need an “atomic” operation to ensure the count is not corrupted by multiple requests.

Testing the Tutorial Server#

Now that we have developed our Tutorial Server we want to test it.

In the code above we have modified the root endpoint to return a message based on the environment variable TUTORIAL_GREETING. Also the counter is initialized through the INITIAL_COUNT environment variable, so that we can control these at start up of the program. We will demonstrate how these can be controlled by the user on an Edge Deployment later in this tutorial.

For the moment can set these variables and test the application. Start the server again with the following command:

TUTORIAL_GREETING="Welcome to the tutorial" INITIAL_COUNT=5 fastapi dev main.py

In a separate terminal, run the command:

curl localhost:8000

and it should reply with:

{"message":"Welcome to the tutorial"}

The other endpoints can be tested in a similar way. For example, to increment the counter:

curl -X POST localhost:8000/increment

and it should reply with:

{"count":6}

Because Fast API generates a REST API out of these specially annotated functions, it is easy to produce a client to test it. Indeed opening a Web Browser and going to http://localhost:8000/docs will show the Swagger* UI, which can be used directly

The OpenAPI 3.1 specification for the Tutorial Server can be found at http://localhost:8000/openapi.json and imported in to many tools such as Postman or Insomnia.