Managing Python dependencies can be hard, especially as projects get bigger. It's important to have the right packages and versions installed without conflicts. Poetry helps with this. It's a tool that makes managing project dependencies, packaging, and publishing easier. In this article, we'll show you how to use Poetry to manage Python dependencies, make your workflow smoother, and keep your project setup clean and efficient.
In this blog, you will learn how to:
Install Poetry on your system
Create a new Poetry project
How to run fastapi server with poetry
Installing Poetry
Reference: python-poetry.org/docs/#installation
curl -ssl https://install.python-poetry.org | python3 -
Create a new Poetry Project
poetry new awesome-project
This will create a fresh poetry project with a directory structure like this
Pyproject.toml
Poetry manages all the dependencies with the help of the pyproject.toml
, It is similar to the package.json
in a node project
[tool.poetry]
name = "awesome-project"
version = "0.1.0"
description = ""
authors = ["Your Name <you@example.com>"]
readme = "README.md"
[tool.poetry.dependencies]
python = "^3.12"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
Activate a virtual environment
You can list all the virtual environments available in poetry
poetry shell
Let's make a simple hello world FastAPI Server
Adding fastapi and uvicorn as dependencies
poetry add fastapi uvicorn
Now if you check the pyproject.toml, fastapi and uvicorn are added as dependencies
Write a basic fastapi server
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, World!"}
To run the server lets start by using the following command
poetry run uvicorn main:app --reload
And as expected the server is in a good condition
By following the steps outlined in this article, you can effectively manage your Python dependencies using Poetry. This powerful tool not only simplifies dependency management but also enhances your workflow, ensuring that your projects remain clean, efficient, and free from conflicts. Whether you're starting a new project or maintaining an existing one, Poetry provides the structure and reliability needed to keep your development process smooth and hassle-free. Happy coding!