DEV Community

Cover image for Getting Started with FastAPI - Create APIs Quickly using Python

Getting Started with FastAPI - Create APIs Quickly using Python

supanthapaul profile image Supantha Paul ・5 min read

I've recently started learning FastAPI and comparing it to my trusty framework of choice (Express), and I think come to really like its simple nature. FastAPI defines itself as a "modern, fast (high-performance), web framework for building APIs with Python". In this article, I'll try to get you up and running with FastAPI by building a simple Pizza API!


You can install FastAPI by running the following command,

pip install fastapi
Enter fullscreen mode Exit fullscreen mode


You can use either uvicorn or hypercorn for the server, both are great and do the same thing. I'll be using uvicorn for this tutorial. You can install them by running the following command,

pip install uvicorn
Enter fullscreen mode Exit fullscreen mode


pip install hypercorn
Enter fullscreen mode Exit fullscreen mode

That's all we need for this tutorial, let's get to the fun part!

Getting Started

Before creating the Pizza routes, let's first create a simple base route that returns a simple JSON response.
Create a directory for your project and create a file. Your code should look something like this (Feel free to change the name of your Pizza hub!).

# Import FastAPI
from fastapi import FastAPI

# Initialize the app
app = FastAPI()

# GET operation at route '/'
async def index():
    return {"greeting" : "Welcome to Paul's Pizza!"}
Enter fullscreen mode Exit fullscreen mode

Running the live server

You can run the live server with uvicorn using the following command,

uvicorn main:app --reload
Enter fullscreen mode Exit fullscreen mode

Notice that in the code, 'main' refers to the file name and 'app' is the name of the FastAPI instance that we created previously.

If you now visit localhost:8000 from your browser, you'll see the following JSON response,
Simple response

Things to note

  1. Notice that in the code, @app.get("/") tells FastAPI that the function below is in charge of handling requests that go to,
    • Path /
    • using the get HTTP method. Similarly, you can use other HTTP methods like put, post, or delete.
  2. FastAPI generates automatic API documentation using Swagger. You can visit the docs by visiting localhost:8000/docs. You can also test your API endpoints from here, how neat!

    At this point, your API docs should look like this with only the '/' route,
    API docs

  3. Another thing to notice is, FastAPI automatically converts python dicts, lists, or other primitive types or Pydantic models to suitable JSON format, no need to do that yourself!

Enough with the basics, let's create our Pizza API now!

Creating the Pizza API

Let's now create a simple API where we have a list of pizzas with different properties in, let's say, /pizzas and we can get and add more pizzas to the list.

Setting up

Now we could connect to any kind of database that we want but for the sake of simplicity, let's have an in-memory list that we access and modify.

Create a new variable db and initialize it with the following pizza data,

db = [
        'id': 0,
        'name': 'Neapolitan Pizza',
        'toppings': ['Mozzarella cheese', 'Tomatoes', 'Basil']
        'id': 1,
        'name': 'Chicago/Deep-Dish Pizza',
        'toppings': ['Cheese', 'Tomatoes', 'pepperoni', 'Onions', 'Mushrooms']
Enter fullscreen mode Exit fullscreen mode

Getting all pizzas

For a get request at /pizzas we can simply return the db list we created earlier which contains all the pizzas.

# ...
# get all pizzas
async def index():
    return db
# ...
Enter fullscreen mode Exit fullscreen mode

Now if we visit localhost:8000/pizzas we get the list of pizzas we created earlier,

pizzas get
Neat! You can also see the route on the docs (localhost:8000/docs).

Getting a single pizza

Let's create a route for localhost:8000/pizzas/<id> which will return the pizza details for the pizza with the specified id. This is where we'll use path parameters!

# ...
# get a pizza by id
async def get_pizzas(pizza_id):
    for pizza in db:
        if(pizza['id'] == int(pizza_id)):
            return pizza
    return {"error": "Pizza not found with id: " + pizza_id}
# ...
Enter fullscreen mode Exit fullscreen mode

The main thing to note here is that the value of the path parameter pizza_id will be passed to your function as the argument pizza_id which is then used here to return the pizza object with the given id.

So, if you now go to localhost:8000/pizzas/0, you will see a response like this,

Single pizza
Great! But 2 types of pizzas aren't enough. Let's see how we can create a post route to add more pizzas to our list!

Adding a new pizza

Let's create a post route on /pizzas for adding new pizzas to our list. For this, we first need to define the data model of our request body, i.e, the kind of data we're supposed to receive from the request.

Our data model here is very simple. We have the name of our pizza which is a string and a list of toppings. We'll generate a new id for the pizza dynamically. We define the data model by inheriting the BaseModel class from Pydantic,

from pydantic import BaseModel
from typing import List

# pizza model
class Pizza(BaseModel):
  name: str
  toppings: List[str]
Enter fullscreen mode Exit fullscreen mode

We can now use this Pizza class as a type for our request body. Here's how we're going to create the post method,

async def post_pizza(pizza: Pizza):
    # convert to dictionary
    new_pizza = pizza.dict()
    # add a new id
    new_pizza['id'] = db[-1]['id'] + 1
    # add to list
    return new_pizza
Enter fullscreen mode Exit fullscreen mode

You can test this post route directly from our API docs at localhost:8000/docs by clicking the Try it out button under the POST route we just created and passing the request body,
API docs 2
If we execute this request and visit localhost:800/pizzas, we'll see that our new pizza has been added to the list and an id is also generated!

All pizzas 2

Final words

Great job! You've created a simple API that accepts GET and POST requests with such little code. If you like what you see and want to explore FastAPI more, I suggest going through the FastAPI User Guide for a more in-depth look at the most important features. For a starter, try adding a PUT and DELETE route for the pizzas!

If you'd like to chat with me about anything technology or just say hi, you can Connect with me on LinkedIn or Find me on Twiiter. My DMs are open!

I'm leaving the full file that we worked on here if you want to refer to it, cheers!

Discussion (2)

Editor guide
envoy_ profile image

Hey nice article can u suggest how to deploy this api using flask or any other to firebase/vercel/GitHub pages

supanthapaul profile image
Supantha Paul Author

You'd need a server for deploying APIs like these, like Heroku for example.