Skip to content

ivorscott/fastapi

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 

Repository files navigation

fastapi

Preparing a virtual environment

# Create virtual environment

python3 -m venv .venv

# Activate virtual environment

. .venv/bin/activate

# Install packages

pip install fastapi
pip install uvicorn

Using pip

pip is the package installer for Python. https://pypi.org/project/pip/

# Installing packages

pip install <package>


# Uninstall packages

pip uninstall <package>

# Listing packages

pip list 

# Listing outdated packages

pip list --outdated

Running an application

mkdir books
cat > books/books.py <<EOF
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def hello():
    return "hello world"
EOF

# 1. Running app in PARENT_DIRECTORY & reloading if files change

uvicorn books.books:app --reload 
# SYNTAX
# books.books:app = (directory).(python_file):(name_of_app_instance)

# 2. Running app in CURRENT_DIRECTORY & reloading if files change

cd books
uvicorn books:app --reload

Swagger

FastAPI ships with swagger by default. http://localhost:8000/docs

https://swagger.io/solutions/api-design/

  • Use verbose snake case names for api endpoint functions. Swagger will use the name as an endpoint
  • Function comments will be used as a description.
@app.get("/books")
async def read_all_books():
    return BOOKS

Path parameters

You can declare path "parameters" with the same syntax used by Python format strings:

@app.get("/books/{book}")
async def read_book(book: str):
    return {'book', book}

Endpoint priority

Endpoint order matters, they are read from top to botoom. For example, the last endpoint below won't match because it overlaps with the endpoint above it. To fix this flip the order. Rule of thumb, add dynamic parameter endpoints last.

@app.get("/books/{book}")
async def read_book(book:str):
    return {'book', book}

@app.get("/books/mybook")
async def read_book():
    return {'book', "my book"}

Query parameters

Unlink path parameters, query parameters are not defined in the path but included in the function parameters.

@app.get("/books/{book}/")
async def read_book(book:str, query: str):
    return {'book', book, 'query': query}

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages