Learning FastAPI with a sample python library

harisharavindan

Harish Aravindan

Posted on January 4, 2023

Learning FastAPI with a sample python library

what is it about

While I was learning about flask found a very good way to create API with fastAPI.

So wanted to share what I tried out with that framework using a sample pypi package created for encoding reserved characters.

what are we building

API which allows us to encode reserved characters or give a template on what to encode. This is exposed as API though the fastAPI framework.

clone the repo

https://github.com/uptownaravi/LearnfastAPI.git
Enter fullscreen mode Exit fullscreen mode

switch to the fast folder

setup virtual environment

python -m venv venv
.\venv\Scripts\Activate.ps1
Enter fullscreen mode Exit fullscreen mode

this creates a virtual environment where we can install our packages and run the code.
I am using windows so Activate.ps1
if you are using linux run ./venv/bin/activate

run the pip requirements

pip install -r .\requirements.txt
Enter fullscreen mode Exit fullscreen mode

this installs the fastapi, uvicorn for the api and the sample library encodepacakge

start the server

uvicorn main:app --reload
Enter fullscreen mode Exit fullscreen mode

The good thing about fastAPI is we can interact through UI in a browser instead of relying only on cli to run the api

check the url http://127.0.0.1:8000/docs

fastAPIWebPageScreenShot

expand the second section and click on the try it out button

tryoutencodeapi

add details to the data field and click on execute

encodeAPIOutput

what happened in the above step

if you check the main.py file

@app.get("/encode/{data}")
def encodedata(data: str):
    encodedata = enc.encoded(data)
    return f"encoded value of {data} is {encodedata}"
Enter fullscreen mode Exit fullscreen mode

we are calling the Encode class to update the reserved character like mypass#50 into mypass%2350.

as we are exposing this as api we can visit the url http://127.0.0.1:8000/encode/mypass%2350 to get the output as well

this can be extended by adding the required endpoints to the main.py with supporting python files.

Will add more examples as I explore more on fastAPI

reference

fastAPI - https://fastapi.tiangolo.com/

💖 💪 🙅 🚩
harisharavindan
Harish Aravindan

Posted on January 4, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related