How to install and use FastAPI

FastAPI is a web framework for developing RESTful APIs in Python. It is based on pydantic and type hints to validate, serialize and deserialize data and automatically auto-generate OpenAPI documents.

Features of FastAPI

  • Fast
  • Fast to code with
  • Fewer bugs
  • Intuitive has a code editor completion feature
  • Easy to learn and use.
  • Has minimized code duplication
  • Robust, you get production-ready code
  • Standards-based. It’s entirely based on open standards

Installing FastAPI

To start using FastAPI, you need to install it on your system, then after that, install ASGI server to run on such Uvicorn or Hypercorn.

To install FastAPI run the following command from the terminal pip install fastapi

pip install fastapi

Next is to install a server that is Uvicorn pip install "uvicorn[standard]"

pip install "uvicorn[standard]"

That is all about the installation. Let’s see an example of FastAPI. Create a project folder and cd into the project folder. Open the project on your preferred code editor. Create a main.py file and paste it .0into the following code.

from fastapi import FastAPI

app = FastAPI()

@app.get('/')
def root():
    return {'Message': 'World'

To run the above code use the following command uvicorn main:app --reload

uvicorn main:app --reload

--reload tells the server to reload every time new changes are introduced.

If it starts the server correctly, you will be in a position to see the following as the output.

INFO:     Will watch for changes in these directories: ['/home/sang-pc/Documents/dev/fastapi/project']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [3192] using WatchFiles
INFO:     Started server process [3194]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

To see the changes, now go to the browser and open http://127.0.0.1:8000, you will see your message on the browser.

Accessing Interactive API docs

To access a more interactive API user interface, use docs UI. To access docs UI run the following from your browser.

http://127.0.0.1:8000/docs

Yow will see a very clean UI to test your project

Nextgentips: Fastapi Swagger UI
Nextgentips: Fastapi Swagger UI

If you love terminal, you can still get the results by using the curl command like this:

curl -X 'GET' \
  'http://127.0.0.1:8000/' \
  -H 'accept: application/json'

From here now you can start writing your restful API logic.

About Mason Kipward

I am a technology enthusiast who loves to share gained knowledge through offering daily tips as a way of empowering others. I am fan of Linux and all other things open source.
View all posts by Mason Kipward →

Leave a Reply

Your email address will not be published. Required fields are marked *