FastAPI is a modern tool used for constructing APIs with Python 3.7 and above, utilizing standard Python type hints.

It's recognized for its quickness, user-friendliness, and the ability to automatically generate interactive API documentation.

When combined with a proficient Object-Relational Mapping (ORM) library such as PonyORM, it transforms into a robust instrument for developing scalable and manageable web applications.

In this article, we will look into the process of setting up and utilizing PonyORM in conjunction with FastAPI to effortlessly create and use databases.


Why Choose PonyORM?

PonyORM website at https://ponyorm.org/

PonyORM is an Object-Relational Mapping (ORM) tool specifically designed for Python, employing a distinct method to link Python objects with database tables.

Here are some of its standout features:

  • Declarative Mapping: PonyORM utilizes Python generators to formulate queries, making them straightforward to understand and compose.
  • User-Friendliness: With features like automatic schema creation and a user-friendly API, PonyORM streamlines the process of managing databases.
  • Compatibility with Numerous Databases: PonyORM is versatile, offering support for SQLite, MySQL, PostgreSQL, and Oracle databases.

Are you tired of writing the same old Python code? Want to take your programming skills to the next level? Look no further! This book is the ultimate resource for beginners and experienced Python developers alike.

Get "Python's Magic Methods - Beyond __init__ and __str__"

Magic methods are not just syntactic sugar, they're powerful tools that can significantly improve the functionality and performance of your code. With this book, you'll learn how to use these tools correctly and unlock the full potential of Python.

Setting Up FastAPI with PonyORM

Step 1: Install the Required Packages

First, you need to install FastAPI, PonyORM, and an ASGI server, such as Uvicorn. You can do this using pip:

pip install fastapi uvicorn pony

Step 2: Create a FastAPI Application

Start by creating a simple FastAPI application. In a new file main.py, set up the basic structure of your application:

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def read_root():
    return {"Hello": "World"}

Step 3: Configure PonyORM

Next, configure PonyORM to connect to your database. For this example, we'll use SQLite for simplicity.

from pony.orm import Database, Required, db_session

db = Database()


class User(db.Entity):
    username = Required(str)
    email = Required(str)


db.bind(provider='sqlite', filename='database.sqlite', create_db=True)
db.generate_mapping(create_tables=True)

Step 4: Integrate PonyORM with FastAPI

To ensure that PonyORM's sessions are correctly managed, we will use FastAPI's dependency injection system. This will help manage the database session within the context of each request:

def get_db_session():
    with db_session:
        yield

@app.post("/users/")
async def create_user(username: str, email: str, db: db_session = Depends(get_db_session)):
    user = User(username=username, email=email)
    return user.to_dict()

@app.get("/users/")
async def get_users(db: db_session = Depends(get_db_session)):
    users = User.select()
    return [user.to_dict() for user in users]

Step 5: Run the Application

Now, you can run your FastAPI application using Uvicorn:

uvicorn main:app --reload

Navigate to http://127.0.0.1:8000/docs to see the automatically generated interactive API documentation provided by FastAPI.

You can then create a user like this:

Creating a user by sending a POST request

Which should give you this response:

Response to the POST request to create a user

You can confirm that the user was created successfully with:

GET request to get the list of users

Conclusion

Merging FastAPI with PonyORM enables you to swiftly construct robust and maintainable web applications.

FastAPI's up-to-date features, like automatic validation and interactive documentation, coupled with PonyORM's intuitive and potent database mapping, foster a productive development environment.

This configuration is perfect for developers aiming to create efficient APIs while minimizing repetitive code.

Tagged in: