Post

Getting Started with FastAPI

What is FastAPI?

FastAPI is a modern, high-performance, web framework for building APIs with Python 3.6+ based on standard Python type hints. It is built on top of Starlette and Pydantic, two of the most popular libraries in the Python ecosystem.

Why use FastAPI?

FastAPI is a great choice for building APIs because it is fast, easy to use, and has a lot of features that make it easy to build APIs. It also has a lot of great documentation and examples that make it easy to get started.

How to get started with FastAPI?

To get started with FastAPI, you can follow the official documentation. It is very well written and easy to follow.

Setup FastAPI with poetry

Create a new project using poetry

1
2
poetry new fastapi-docker
cd fastapi-docker

Add dependencies to poetry

1
poetry add fastapi "uvicorn[standard]"

Above command will add fastapi and uvicorn to your project.

pyproject.toml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[tool.poetry]
name = "fastapi-docker"
version = "0.1.0"
description = ""
authors = [""]
readme = "README.md"

[tool.poetry.dependencies]
python = "^3.11"
fastapi = "^0.103.0"
uvicorn = {extras = ["standard"], version = "^0.23.2"}



[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

Install dependencies

1
poetry install

Create a new file main.py

1
2
3
4
5
6
7
8
9
from fastapi import FastAPI

app = FastAPI()


@app.get("/say_hello")
async def say_hello(message: str):
    return {"message_sent": message}

Run the application

1
2
3
4
5
6
7
8
9
10
11
12
cd fastapi_docker
poetry run uvicorn main:app --reload

Output:
INFO:     Will watch for changes in these directories: ['<workspace_path>/fastapi-docker/fastapi_docker']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [12559] using WatchFiles
INFO:     Started server process [12563]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     127.0.0.1:61692 - "GET /docs?vscodeBrowserReqId=1693646432978 HTTP/1.1" 200 OK
INFO:     127.0.0.1:61692 - "GET /openapi.json HTTP/1.1" 200 OK

Go to http://localhost:8000/docs to see the swagger documentation.

You don’t need to use poetry tool to setup the FastAPI project but it is recommended to use it. You can also use pip to install the dependencies.

FastAPI Swagger

Write Tests

Create test_api.py file for above logic under tests folder.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from fastapi.testclient import TestClient

from fastapi_docker.main import app


client = TestClient(app)


def test_say_hello():
    response = client.get("/say_hello?message=hello")
    assert response.status_code == 200
    assert response.json() == {"message_sent": "hello"}


def test_say_hello_no_message():
    response = client.get("/say_hello")
    assert response.status_code == 422
    assert response.json() == {
            "detail": [
                {
                    "type": "missing",
                    "loc": ["query", "message"],
                    "msg": "Field required",
                    "input": None,
                    "url": "https://errors.pydantic.dev/2.3/v/missing",
                }
            ]
    }

Run Tests

1
2
3
4
5
6
7
8
9
10
11
12
13
14
pytest tests/test_api.py

Output:
================ test session starts ================
platform darwin -- Python 3.11.2, pytest-7.4.0, pluggy-1.3.0
rootdir: /python/fastapi-docker
plugins: anyio-4.0.0
collected 2 items 


tests/tests_api.py  [100%]

=================== 2 passed in 0.26s ===================

This post is licensed under CC BY 4.0 by the author.