FastAPI

Setup Development Environment

Prerequisite

I have Python 3.12.2 installed on Mac.

Check Python Version
$ python3 -V

Package and Dependency Management

We can use Poetry for Python packaging and dependency management. We need to install pipx first.

pipx install command
brew install pipx
pipx ensurepath

Install poetry:

pipx install command
pipx install poetry

Check version:

poetry version
$ poetry --version
Poetry (version 1.8.2)

Open a new terminal and run:

Bash Autoloaded
poetry completions bash >> ~/.bash_completion

Formatting Code

For formatting source code:

Source Code Formatter
$ pip install black

Testing

For testing:

Install Pytest
$ pip install pytest

FastAPI Setup

Install FastAPI framework:

FastAPI Install Command
pip install fastapi

An asynchronous web server:

Install Server Command
pip install uvicorn

To hit the API from the terminal:

Install HTTP Client
pip install httpie

A synchronous web client package:

HTTP Client for Python Console
pip install requests

A synchronous/asynchronous web client package

HTTP Client for Python Console
pip install httpx

Hello FastAPI

We can now check our development setup. Create a hi.py file:

hi.py
from fastapi import FastAPI

api = FastAPI()

@api.get("/")
def greet():
    return {"message": "Hello FastAPI"}
Start Uvicorn Server
$ uvicorn hi:api --reload

View the response in the browser at: http://127.0.0.1:8000/

Command Line HTTP Client

Use http in the terminal:

Hit the API endpoint
$ http http://127.0.0.1:8000/
Server Response
HTTP/1.1 200 OK
content-length: 27
content-type: application/json
date: Sun, 31 Mar 2024 15:32:48 GMT
server: uvicorn

{
    "message": "Hello FastAPI"
}
View only response
$ http -b http://127.0.0.1:8000/
JSON response
{
    "message": "Hello FastAPI"
}
Verbose Switch
$ http -v http://127.0.0.1:8000/
Verbose Response
GET / HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Host: 127.0.0.1:8000
User-Agent: HTTPie/3.2.2

HTTP/1.1 200 OK
content-length: 27
content-type: application/json
date: Sun, 31 Mar 2024 15:33:52 GMT
server: uvicorn

{
    "message": "Hello FastAPI"
}