FastAPI Tutorial for Beginners

So what makes it so great? Well, for starters, it’s really fast! Like, lightning-fast! And that’s because it uses Starlette as its underlying framework instead of WSGI like most other web frameworks do. This means that your code runs faster and more efficiently, which is always a good thing when you’re dealing with large datasets or complex algorithms.

FastAPI is designed to be beginner-friendly, so we won’t be diving too deep into the technical details just yet. Instead, let’s start by creating a simple API that returns some basic information about our favorite animals: cats and dogs.

First, we need to install FastAPI using pip (which is like a package manager for Python). To do this, open up your terminal or command prompt and type the following command:

# This line installs FastAPI using pip, a package manager for Python
pip install fastapi

Once that’s done, create a new file called `main.py` in your project directory and add the following code inside it:

# Import the necessary module FastAPI
from fastapi import FastAPI
# Import the random module to generate random values
import random

# Create an instance of the FastAPI class
app = FastAPI()

# Define a route for the root endpoint
@app.get("/")
def read_root():
    # Return a dictionary with a "Hello" key and "World" value
    return {"Hello": "World"}

# Define a route for the "/animals/cat" endpoint
@app.get("/animals/cat")
def get_cat():
    # Create a list of cat names
    names = ["Whiskers", "Mittens", "Fluffy"]
    # Create a list of cat ages
    ages = [3, 5, 7]
    # Create a list of cat breeds
    breeds = ["Siamese", "Persian", "Bengal"]
    # Return a dictionary with a random name, age, and breed for a cat
    return {"name": random.choice(names), "age": random.choice(ages), "breed": random.choice(breeds)}

# Define a route for the "/animals/dog" endpoint
@app.get("/animals/dog")
def get_dog():
    # Create a list of dog names
    names = ["Max", "Rex", "Buddy"]
    # Create a list of dog ages
    ages = [2, 4, 6]
    # Create a list of dog breeds
    breeds = ["Labrador Retriever", "Golden Retriever", "German Shepherd"]
    # Return a dictionary with a random name, age, and breed for a dog
    return {"name": random.choice(names), "age": random.choice(ages), "breed": random.choice(breeds)}

This code defines two endpoints (also known as routes) that handle requests for information about cats and dogs, respectively. The `read_root()` function simply returns a JSON object with the message “Hello World”. The other two functions generate random data for each animal based on their name, age, and breed.

To run this code, save it in your project directory (let’s call it `myproject`) and navigate to that directory using your terminal or command prompt:

# This script navigates to the project directory named "myproject"
cd myproject

# This function generates random data for a dog based on its name, age, and breed
function generate_dog_data() {
  # Assigns a random name to the dog
  name=$(shuf -n 1 dog_names.txt)
  # Assigns a random age to the dog
  age=$(shuf -i 1-10 -n 1)
  # Assigns a random breed to the dog
  breed=$(shuf -n 1 dog_breeds.txt)
  # Prints out the generated data in a JSON format
  echo '{"name": "'"$name"'", "age": '"$age"', "breed": "'"$breed"'"}'
}

# This function generates random data for a cat based on its name, age, and breed
function generate_cat_data() {
  # Assigns a random name to the cat
  name=$(shuf -n 1 cat_names.txt)
  # Assigns a random age to the cat
  age=$(shuf -i 1-10 -n 1)
  # Assigns a random breed to the cat
  breed=$(shuf -n 1 cat_breeds.txt)
  # Prints out the generated data in a JSON format
  echo '{"name": "'"$name"'", "age": '"$age"', "breed": "'"$breed"'"}'
}

# This function generates random data for a bird based on its name, age, and breed
function generate_bird_data() {
  # Assigns a random name to the bird
  name=$(shuf -n 1 bird_names.txt)
  # Assigns a random age to the bird
  age=$(shuf -i 1-10 -n 1)
  # Assigns a random breed to the bird
  breed=$(shuf -n 1 bird_breeds.txt)
  # Prints out the generated data in a JSON format
  echo '{"name": "'"$name"'", "age": '"$age"', "breed": "'"$breed"'"}'
}

# Calls the generate_dog_data function and assigns the output to a variable
dog_data=$(generate_dog_data)
# Calls the generate_cat_data function and assigns the output to a variable
cat_data=$(generate_cat_data)
# Calls the generate_bird_data function and assigns the output to a variable
bird_data=$(generate_bird_data)

# Prints out the final JSON object with the message "Hello World" and the generated data for each animal
echo '{"message": "Hello World", "dog": '"$dog_data"', "cat": '"$cat_data"', "bird": '"$bird_data"'}

Then start the FastAPI server by running the following command:

# This script starts the FastAPI server by running the following command:
# uvicorn main:app --reload

# The following line imports the uvicorn library, which is used to run the FastAPI server.
import uvicorn

# The following line defines the main function, which is used to run the FastAPI server.
def main():
    # The following line specifies the app to be used by the FastAPI server.
    app = "main:app"
    # The following line specifies the reload option, which automatically reloads the server when changes are made to the code.
    reload = True
    # The following line starts the FastAPI server using the specified app and reload options.
    uvicorn.run(app, reload=reload)

# The following line calls the main function to start the FastAPI server.
main()

This will launch a web server on port 8000 and automatically reload your code whenever you make changes to it. To test this out, open up your browser and navigate to `http://localhost:8000`. You should see the message “Hello World” displayed in JSON format.

Now let’s try accessing our animal endpoints by visiting `http://localhost:8000/animals/cat` and `http://localhost:8000/animals/dog`, respectively. These URLs will return a random cat or dog object with their name, age, and breed.

That’s it! You now have a basic understanding of how to use FastAPI for building web APIs in Python. In future tutorials, we’ll dive deeper into the framework’s features and capabilities, but for now let’s just enjoy our newfound speed and efficiency!

SICORPS