Developing a type-safe Python API with FastAPI and EdgeDB 🚀

Posted by

FastAPI + EdgeDB for a type-safe Python API

FastAPI + EdgeDB for a type-safe Python API

Python has always been a popular language for building web APIs, and with the introduction of FastAPI and EdgeDB, it has become even more powerful. FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It provides automatic interactive API documentation and validation, and is built on top of Starlette for the web parts and Uvicorn for the ASGI server. EdgeDB, on the other hand, is a modern, high-performance, open-source object-relational database designed for building complex and scalable applications without sacrificing developer productivity or the schema flexibility of NoSQL databases.

When using FastAPI and EdgeDB together, you can build a type-safe Python API with ease. FastAPI’s support for type hints and automatic validation ensures that you write clean, error-free code while EdgeDB’s powerful query language and sophisticated data modeling capabilities make it simple to work with complex data structures.

To get started, you can install FastAPI and EdgeDB using pip:


pip install fastapi
pip install edb

Once you have them installed, you can start building your API using FastAPI’s intuitive syntax and EdgeDB’s powerful data modeling features. Here’s a simple example of how you can define a type-safe API endpoint using FastAPI and EdgeDB:


from fastapi import FastAPI
import edgeql

app = FastAPI()

@app.get("/users/{user_id}")
async def get_user(user_id: int):
conn = await edgeql.connect(edgedb_dsn="edgedb://...") # replace ... with your EdgeDB DSN
user = await conn.fetch_one(
"SELECT User { id, name } FILTER .id = $user_id",
user_id=user_id
)
await conn.aclose()
return user

In this example, we define a GET endpoint that takes a user_id as a path parameter and returns a user with the corresponding ID from the EdgeDB database. FastAPI automatically validates the input and EdgeDB efficiently fetches the user data based on the query. The result is a type-safe, efficient API with minimal boilerplate code and maximum developer productivity.

With FastAPI and EdgeDB, building a type-safe Python API has never been easier. Their powerful combination of modern web framework and high-performance database allows you to focus on writing clean, error-free code and building scalable, complex applications without sacrificing developer productivity. Whether you are building a small API or a large-scale application, FastAPI and EdgeDB are the perfect tools for the job.

0 0 votes
Article Rating
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@seungwonjeong5470
9 months ago

nice video! how do I install edgedb-py?

@lolnaha
9 months ago

when will I be able to generate pydantic models from my edgedb schema?

@SergeyLyapustin
9 months ago

Nice, thanks!