Getting Started with FastAPI – Create APIs Quickly using Python

Getting Started with FastAPI – Create APIs Quickly using Python:

 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!

Installation

You can install FastAPI by running the following command,

pip install fastapi

Server

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

Or,

pip install hypercorn

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 main.py file. Your code should look something like this (Feel free to change the name of your Pizza hub!).

# main.py
# Import FastAPI
from fastapi import FastAPI

# Initialize the app
app = FastAPI()

# GET operation at route '/'
@app.get('/')
async def index():
    return {"greeting" : "Welcome to Paul's Pizza!"}

Running the live server

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

uvicorn main:app --reload

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,

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 putpost, 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,

  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,

# main.py
#...
db = [
    {
        'id': 0,
        'name': 'Neapolitan Pizza',
        'toppings': ['Mozzarella cheese', 'Tomatoes', 'Basil']
    },
    {
        'id': 1,
        'name': 'Chicago/Deep-Dish Pizza',
        'toppings': ['Cheese', 'Tomatoes', 'pepperoni', 'Onions', 'Mushrooms']
    },
]
#...

Getting all pizzas

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

# main.py
# ...
# get all pizzas
@app.get('/pizzas')
async def index():
    return db
# ...

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


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/ which will return the pizza details for the pizza with the specified id. This is where we’ll use path parameters!

# main.py
# ...
# get a pizza by id
@app.get('/pizzas/{pizza_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}
# ...

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,


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,

# main.py
#...
from pydantic import BaseModel
from typing import List

# pizza model
class Pizza(BaseModel):
  name: str
  toppings: List[str]
#...

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,

# main.py #...
@app.post('/pizzas')
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
    print(new_pizza)
    db.append(new_pizza)
    return new_pizza
#...

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,


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!

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!

from Tumblr https://generouspiratequeen.tumblr.com/post/642312118273720320

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s