Start your first FastAPI server with Poetry in less than 10 minutes

Gustavo Caetano
2 min readMay 10, 2022

--

It is possible to mange your FastAPI application without poetry, however Poetry provides us a better experience to manage our application, this experience is close to the one provided by NodeJS with npm. The following article teaches you how to start a simple application with them.

Poetry installation

To build the application, the first step is download the poetry. You can do it typing the following piece of code in your terminal (linux/macOS):

curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python -

If you are using Windows, it is possible to use this command to download Poetry:

(Invoke-WebRequest -Uri https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py -UseBasicParsing).Content | python -

To check if your installation went well, you can paste the following poetry command:

poetry --version

Starting the application

Now we will start our development environment, for it we still need poetry to manage our dependencies and also start the virtual environment.

With the following command the project will start, note that you should open the terminal in the project folder to start the project in the right path.

poetry init 

Then a .toml file should be created and in this file you can add your dependencies (the libraries that you will use during the project).

The last thing before we start to build our application that we need is: install FastAPI. To install it with poetry, it is really simple as shown below:

poetry add fastapi uvicorn[standard]
  • FastAPI — It is the web framework
  • uvicorn — Uvicorn is an ASGI web server implementation for Python.

To activate the virtual env, remember to paste the code below in your terminal

poetry shell

Building the server

Firstly we need to create a new python file called main.py, this file will contain our route and also the app object, this object is responsible to instantiate the FastAPI properly.

from fastapi import FastAPI  app = FastAPI()   @app.get("/") 
async def main_route():
return {"message": "Hey, It is me Goku"}

Finally your application can start, for that the command shown below is needed:

uvicorn main:app — reload

Now your application is running on http://127.0.0.1:8000 and the good news is: FastAPI is integrated with Swagger, the documentation is automatically generated and you can check it in the docs/.

Next session

The next session, I will write about FastAPI and Pytest, that is, how you can write tests for your routes, dependencies and etc.

See you soon !

--

--