Build API’s fast using FastAPI and Python
By: Priyav K Kaneria
Tags: Programming, Coding, Django, Github, Python

Understanding the code

Now the time has come to understand the code line by line.

Let us start with main.py -

First of all, line 1 to 4 says that

from fastapi import FastAPI, Request

from fastapi.responses import RedirectResponse

from fastapi.templating import Jinja2Templates

import json

we have imported the required functions from fastapi and imported json. The RedirectResponse function will help us redirect to the main-page after going to add or delete API. The Jinja2Templates will be useful for using templates while parsing data and variables in templates. We are also using json library to store and read data from a json file which we will use as a database to store our To-do’s.

Next, we can see that we have defined a templates variable by providing a valid templates directory for us to directly use the templates in it.

After that, we have the below code snippet

@app.get("/")

async def root(request: Request):

with open('database.json') as f:

data = json.load(f)

return templates.TemplateResponse("todolist.html",

"request":request,"tododict":data})

Here we open our database.json and read it’s content using the loads function from json library. The data is passed to the template using the dictionary object in the TemplateResponse function. This function renders the template for us, whose name we provide as first parameter and parses the variables, we pass as dictionary object in the template.

It is necessary to provide the request variable to the template for rendering.

Let us now jump to the todolist.html template and understand it first before moving on in main.py .

{% for id in tododict %}

<tr>

<td>{{ tododict[id] }}</td>

<td><a href="/delete/{{ id }}"><button>Delete</button></a></td>

</tr>

{% endfor %}

This is the most confusing/interesting/important part. Here, we are using template formatting to use the variables that were passed and also using Python inside our template. The for loop, loops over the to-do’s and using

{{ variable_name }} as a format we are making a new row for every todo and also making a button along with the todo specifically hyperlinked to the “/delete/( id of the todo )” which we have defined in main.py for deleting the todo. The {% endfor %} provides the template a limit from where to where it has to repeat in for. You will also find the form to add the todo hyperlinked to “/add” to add a new todo.

Coming back to main.py , we can now understand the later defined delete and add API’s.

In delete API, one new thing we can see is, the way in which the api is defined.

It is defined as “/delete/{id}”. Here the curly brackets signify that any variable data can be passed as a API route where the id will be passed as the parameter of the API function.

We are again reading the current database and deleting the specific todo. But importantly we then need to update the database with the latest data which we can do by opening the file in write mode this time (denoted as ‘w’ )and dumping the json in the file.

We are then simply redirecting the user to our mainpage using our imported RedirectResponse function where we pass the redirect_url as “/” and the status code as 303 for temporary redirect.

Alas! The add API is quite easy to understand😁. After reading the data, we are getting the form that was posted from the html by awaiting the request.

Then, we give proper id’s to each task to make sure, we add todo correctly and THEN add our new task. The request provides us formdata type object which is a dictionary, with keys corresponding to the names of the inputs in the form.

The only step left is to update our database and we are done. (After redirecting !😅)

You can also go to http://localhost:8000/docs (while the server is running) and checkout the API’s we made in Swagger UI.

So this is how to make a fast API fast, using FastAPI!