iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐍

Building a REST API with FastAPI and Prisma

に公開

Creating a REST API with FastAPI + Prisma

If you want to create a REST API with Python, combining FastAPI and Prisma allows for very efficient development. In this article, I will explain how to create a simple REST API using FastAPI and Prisma.

When creating a REST API with Python, it is common to use SQLAlchemy as an ORM, but although not widely known, Prisma can also be used with Python. Prisma is an ORM widely used in Node.js and TypeScript, but Prisma Client Python is being developed as a client library for Python.

https://prisma-client-py.readthedocs.io/

By using Prisma Client Python, you can leverage Prisma's benefits such as type safety and automatically generated migration files in Python as well. In this article, I will explain how to create a simple REST API by combining FastAPI and Prisma Client Python.

Environment Setup

First, initialize the project using rye and install the necessary packages.

rye init fastapi-prisma-test
cd fastapi-prisma-test
rye add fastapi "uvicorn[standard]" prisma
rye sync
rye shell

Database Configuration

Create a .env file and set the database connection URL. In this example, we will use SQLite.

.env
DATABASE_URL=file:data/database.db

Next, create the Prisma schema file at prisma/schema.prisma.

prisma/schema.prisma
generator client {
  provider = "prisma-client-py"
  recursive_type_depth = 5
}

datasource db {
  provider = "sqlite"
  url = env("DATABASE_URL")
}

model Message {
  id        String   @id @default(uuid())
  text      String
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

Once the schema file is created, run the migration.

prisma migrate dev

Creating a FastAPI Application

Create a server.py file and implement the FastAPI application.

server.py
from fastapi import FastAPI
from prisma import Prisma

app = FastAPI()
prisma = Prisma()

@app.on_event("startup")
async def startup():
    await prisma.connect()

@app.on_event("shutdown")
async def shutdown():
    await prisma.disconnect()

@app.get("/")
def index():
    return {"message": "Hello, World!"}

@app.post("/message")
async def add_message(message: str):
    return await prisma.message.create(data={"text": message})

@app.get("/message")
async def get_messages(take: int = 10):
    message_count = await prisma.message.count()
    messages = await prisma.message.find_many(take=take)
    return {"message_count": message_count, "messages": messages}

@app.get("/message/{id}")
async def get_message(id: str):
    return await prisma.message.find_first(where={"id": id})

Here, we implement the following endpoints:

  • GET /: Returns a "Hello, World!" message.
  • POST /message: Creates a new message.
  • GET /message: Retrieves a list of messages.
  • GET /message/{id}: Retrieves a specific message.

Also, we use FastAPI's startup and shutdown events to handle the connection and disconnection of the Prisma client when the application starts and shuts down.

Running the Application

Add the following script to the pyproject.toml file.

pyproject.toml
[tool.rye.scripts]
start = { cmd = 'uvicorn server:app --reload' }

Now, you can start the application with the following command:

rye run start

By accessing http://localhost:8000/docs, you can check the API documentation in Swagger UI.

API Usage Examples

Below are examples of how to use the API:

# Creating a message
$ curl -X POST -H "Content-Type: application/json" -d '{"message": "Hello, World!"}' http://localhost:8000/message

# Getting a list of messages
$ curl http://localhost:8000/message

# Getting a specific message
$ curl http://localhost:8000/message/{id}

Conclusion

By using FastAPI and Prisma, you can easily create REST APIs in Python. Prisma's type safety and FastAPI's excellent performance allow for efficient development.

The repository containing the code above is here. I hope it is helpful.
https://github.com/coji/fastapi-prisma-test

Using the methods introduced in this article as a reference, please try creating your own REST API.

GitHubで編集を提案

Discussion