#1 Building an API with FastAPI

İlter Köse
8 min readMar 8, 2021

I’m Ilter from Istanbul, Turkey. I’m Jr Mobile Developer & Junior (3rd Year) EE engineering student who has a passion for software development.

Introduction & Goal

First of all, this article is the first one of the series that I call as “From College Student to College Students.” The main purpose and explanation style will be for college students who get an education with old computer science technique. Why did I define old technique? It is because of time. In college, I learned Java — VHDL — C — Assembly but these languages and frameworks do not help me to get my dream career path which is Mobile Development. When I started to jump mobile application development in 2020, I clearly saw if I want to build a iOS app, I should move on with Swift not Java. Then, I had to learn not only Swift also modern architectures, APIs, modern database technologies, DevOps. Hence, I decided the create a blog series that covers the all steps of making iOS App. However, I am not an expert, I am college student thats why I will make examples from college based lessons, our classic college homeworks. So, welcome the production of “From College Student to College Students.” development series.

credits NASA, reduced gravity walking simulator -represents our baby steps-

What is an API?

API stands for Application Programming Interface. Let me explain with this example;

  • Suppose you are at a pawn shop and you ask for Macbook Pro for seller. Then, we got your order after that it brings the Macbook to you.

Basically, seller is the API and the place with behind the seller is Database or another API.

API is the interface for built the response requests and bring the information which we need. If you are study CS, MIS, Data Science, Software Engineering, Electronics Engineering. You probably heard “database” or had the introduction to database course. Also, you probably make crud operations. CRUD is create, read, update,delete. For instance; In my college, we wrote a Java program which connects the MySQL Database and we create an table which has user modal than we added users, updated them and deleted them. You can ask “Why I need to have an API while I can directly manage the database?” We can ask this questions in many way but “Why should I need to take the Macbook myself while a seller stands in the shop for helping me? Is it safe for company a customer has an access to warehouse?” The answer is the API.

You can use API in order to make your warehouse private, more secure, more organized.

credits tipsta.info

How can I build an API? Why FastAPI should be chosen from you?

You can build an API with many programming languages and frameworks. However, I chose FastAPI for many reasons let me explain them first:

  • Python, FastAPI is build with Python and Python is the easy to use for a college student which had studied Java or C.
  • FastAPI is fast. You can check the documents for detailed information. https://fastapi.tiangolo.com/benchmarks/
  • Swagger UI
  • Easy to install and easy to use with other services. First things first we are newbie for this programming concept. So we dont need to get lost on installation, dependencies, connections with databases.
  • Easy to deploy with ASGI server such as Uvicorn & Hypercorn.

We are ready to go, lets start our journey.

Getting our hands dirty

First things first, you must have Python in your computer. Don’t you know how to check? You can write this to your terminal or command line.

python3 --version

If you see like this message, you are good to go.

Python 3.6.x

Furthermore, we will install FastAPI before that you need to have a virtual environment for keep your project from the main python scripts at your operation system. I suggest you to utilize pipenv package. It generates the virtual environment for you and you can easily install packages with pipenv install then run your projects pipenv run. You can check the pipenv installation at this site. However, I will show the installation with pip.

You can check pipenv with the links below

https://pypi.org/project/pipenv/

https://realpython.com/pipenv-guide/

Lets install the FastAPI. It is so easy write the command to terminal. Then, we need to install a ASGI server for production.

pip3 install fastapipip3 install uvicorn

Nice we are good to go! Now you can open your IDE or Code Editor

Hello API

Lets create a file with name main.py

And then write your first request.

from typing import Optional
from fastapi import FastAPI
app = FastAPI()@app.get('/')
def index():
return {'Hello':'This is my API'}

We are ready to run our code and lets see whats gonna happen. You should write these command to your terminal for running your code.

uvicorn main:app --reload

If you see these lines, congrats you correctly installed and run your project.

Developing the API

Henceforth, we can plan and develop our API. We will learn HTTP Requests also get an experience of APIs and improve our knowledge with mentioning our college lessons. We will move on more detailed operations in next articles.

What is Plan?

  1. I want to make an API when I want a request from It about schools, It should show me.
  2. I want to add new schools for API.
  3. I want to delete a school from the list.

So this plan is basic version of CRUD operations. Lets code!

Quick introduction about HTTP Requests

  • When we want to get all school from database, It is GET Request
  • When we want to add school to database , It is POST Request
  • When we want to delete school from our database, It is DELETE Request

It is easy you can clearly see that.

So, we want to make an API which communicate a database which has School informations.

Step 1: Listing

School is our main data. We can clearly mention this part to your Object Oriented Programming course. I should make a School class with its attributes for listing schools right? After that I need to have a place to keep my data. Today’s section we will keep it so simple place which List ( Array ) in Python.

For defining a School class we need to define as a Model in FastAPI so here I utilized pydantic’s BaseModel by importing it. As I mentioned before, we gonna make a dummy simple database.Thats why, I created an empty list.

In our first point we want to get all school so I need to use GET Request then I only have to return list because all schools will be stored in this list.

from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()class School(BaseModel):
school_name: str
country:str
student_count: int
isAccepting: Optional[bool] = None
database = []@app.get('/')
def index():
return {'Hello':'This is my API'}
@app.get('/schools')
def get_schools():
return database

Step 2: Add

What would you do if you want to add an integer to your list? You just simply use append() method, don’t you? So we will add our function with these simplicity.

First, We need to define type of HTTP Request for adding. It is POST then We need to give parameters for School class attributes, in the end just append to List.

@app.post('/add_schools')
def add_schools(school_id:int,school_name:str,country:str,student_count:str,isAccepting:bool):
new_school = {
"school_id":school_id,
"school_name":school_name,
"country":country,
"student_count":student_count,
"isAccepting":isAccepting
}
database.append(new_school)
return new_school

Congrats! You write your first POST Request. Lets move to the next and last step.

Step 3: Delete

We want to delete a school from our database in order to make it we add school_id in our adding function. So If we give list queue id parameter, we can easily delete school from our database. To make it happen, We will utilize DELETE Request

At this part we do not delete specific item with id, we delete the school with index number. We utilized list for our database, consequently you should start giving id from zero.

@app.delete('/delete_school')
def delete_school(id:int):
return database.remove(database[id])

Now, we are done with intro code. We can move on the testing the functions and API with Swagger UI.

Sending Requests to API with Swagger

FastAPI comes with Swagger UI framework which helps us a lot. It helps us to manage our requests documents easily also testing without any terminal command, any GUI.

Suggestion: You can use Postman for API Requests management.

Entering the Swagger is so easy. Just go to your browser hit your url which has shown when you started uvicorn. Mine is http://127.0.0.1:8000/ then add docs at the end of url. So, If you go http://127.0.0.1:8000/docs then Swagger should welcome you with this page.

From here, we can see what we have done with HTTP Requests. Lets start with listing all schools.

There have no school yet. Because, we havent added yet. So Lets add with our /add_school route and POST Request.

YES! We made it we added a school to database without directly adding database. API worked, you can congrats yourself. Lets add more school then list it again.

Nice we are good to go for our last test. Deleting a school from our database.

This request returned 200 as a Status Code that means request was OK. But It did not return any response body? Because we only assigned the action we did not assigned a returning method action so lets check our database again.

Voila! It is gone and we made it! Everything is 200 and OK! We made an introduction to build an API which makes create, read, delete only with 38 lines of code. FastAPI brings us easy installation, stable servering, understandable UI.

End of the Section

To sum up, We changed our coding style and direction which had thought in college. We created a class like our OOP course then we migrate it to our Database Course with little improvement. From now on, We learned the way how we manage our database operations without directly accessing them. It was my first article in my “From College Student to College Students” series, If I encourage you about building an API with FastAPI, I suggest you to move on documentations, tutorial then get your hands dirty. School is not enough for having a career at FANG and never be. You always have to improve yourself, learning new consepts, make baby steps. This article is my baby step for everything.

In the next episodes, we will improve our API with Tokens, connection to MongoDB Atlas Database for real database actions. After our API and Backend done, I will move on mobile application development. Step by step, I will finish this article series. Thank you, I hope you like it!

For any questions you can email me: ilter.kose@ozu.edu.tr

Repo: https://github.com/ilter/UniFind-API

Django Backend: https://github.com/ilter/UniFind-Django

--

--