FastAPI Quick overview

Advantages:

1. Data validation

  • Traditionally you would write code to check for values to make sure they are the correct type

  • FastAPI does this for you automatically

2. Auto Documentation

  • Can automatically generate documentation that also works kinda like a test script

3. Auto Completion and Code Suggestions

Installation:

pip:

pip3 install fastapi
pip3 install uvicorn

on Linux:

pip install "fastapi[all]"
pip install "uvicorn[standard]"

import:

import fastapi

What is an endpoint?

Example:

  • Endpoints are: /hello /get-item

You would access it by the url below if app is hosted on localhost: localhost/hello

How to create an endpoint in fast-api:

  • Initialize the object

  • use the object followed by .method("/endpoint-path")

  • once the endpoint is reached this will return the dictionary

Types of methods:

  • GET - get info

  • POST - send info

  • PUT - update info

  • DELETE - delete info

Note: This is similar to CRUD in SQL

How to run the server:

cd ~/path/to/project/location.py

# Note: do not add the file extension
uvicorn location:<app name defined in py file> --reload

# Example:
uvicorn first-fastapi-api:app --reload

Testing the API

You can access the link: http://127.0.0.1:8000/docs

This will bring you to the automatically generated API documentation

It documents all API endpoints and you can test them out as well by doing the following:

  1. Select the API Endpoint and click Try it Out:

2. Click Execute:

3. Check the Response Body, or other data that you require:

Endpoint paths

  1. Generate the invetory

  2. Define path of api with GET method

  3. Define the get_item function and specify what type of data is expected

  4. Return data

  • Returns:

  • If you use ID 2 and it is not defined:

  • If you use anything else than integer as defined:

Import Path

  • used to detail endpoints out

  • usually provided to end users

Example:

  1. Import the Path variable

  2. First argument has to be default (In our case None)

  3. Added description of item

  4. Go to the /docs endpoint and now the endpoint should be documented:

Last updated