Getting Started with Python FastAPI: A Beginner’s Guide to High-Performance Web APIs

FastAPI is new light weighted, modern web framework in python that is simple to implement and very much developer friendly. In this blog post we will see how we can create FastAPI in step-by-step manner along with it we will also try to write test case for testing our first FastAPI.

Getting the development environment ready for FastAPI

  1. Create Virtual environment for your first api: If you are using pycharm, then take base environemt as the path of python exe and create a virtual environment
  2. Now its time to install fastapi and uvicorn, where fastapi is web framework to create API’s and unicorn is the server program which is used to run fastapi(venv) PS C:\Users\vikik\Projects\PyProjects\pythonProject\FastAPIDemo> pip install fastapi(venv) PS C:\Users\vikik\Projects\PyProjects\pythonProject\FastAPIDemo> pip install uvicorn

Building the first fastapi program

Now since the environment is ready, we will create a minimal api by instantiating FastAPI

from fastapi import FastAPI

app = FastAPI()

Here first we import FastAPI and then we declare app as an object of FastAPI class, now we will declare our first end point of fastapi

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

Now the next part is running the api using uvicorn [uvicorn main:app –reload or src.uvicorn main:app –reload]

(venv) PS C:\Users\vikik\Projects\PyProjects\pythonProject\FastAPIDemo> uvicorn main:app –reload

INFO:     Will watch for changes in these directories: [‘C:\\Users\\vikik\\Projects\\PyProjects\\pythonProject\\FastAPIDemo’]

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

INFO:     Started reloader process [32676] using WatchFiles

INFO:     Started server process [7572]

INFO:     Waiting for application startup.

INFO:     Application startup complete.

To run it on interactive api documentation

We just need to hit http://127.0.0.1:8000/docs, this is provided by swagger API

Testing our first FastAPI App:

Every application we write need to undergo test case, so we also try to put small minimul test case, the main purpose is to set up testing framework with this.

Project Structure

Here if you see the project structure, we have root as FastAPI Demo under which we have two module

  1. Scr module – which is our logical module for writing API’s
  2. Test folder: which consist of scr module where the test cases are written.

Now since we have segregated the testing from the mail logic, we also need to import main logic to testing module, but direct import of main logic wont work here, because the testing module root path would be

  • ./FastAPIDemo/test/src/test_app.py

Where as the main logic root would be

  • ./FastAPIDemo/src/main.py

So we need to set the sys path to the main program to import the main logic to testing python file to do this, we need to set the path main path in the path variable and this logic we can put in the  __init__.py file of testing module [FastAPIDemo/test/src/__init__.py]

import sys
from pathlib import Path
dir_path = Path(__file__).parent.parent.parent.absolute()
sys.path.insert(1, "C://Users//vikik//Projects//PyProjects//pythonProject//FastAPIDemo//src")

Now lets create a file test_app.py under FastAPIDemo/test/src/test_app.py and put the logic like below

from fastapi.testclient import TestClient
from main import app
import pytest

client = TestClient(app)


def test_root():
    print('a')
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"message": "Hello World"}

Here we are creating an client object of TestClient Class, then we have created a method with test prefix test_root(), here we tries to call the end point using client.get(“/”) to get the json response.

Then we check two things

assert response.status_code == 200
assert response.json() == {"message": "Hello World"}
  • One whether the response status code is 200
  • Second where the json return string from main program is {“message”: “Hello World”}

If both the assert satisfies then the test case will pass.

We can see our first test case is successful 😊. In next post we will put our focus on path parameter.

Happy Coding!

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *