Пример CRUD с использованием FastAPI
FastAPI CRUD Example
Here is a quick example of how you can implement CRUD operations using FastAPI, a modern, fast (high-performance) web framework for building APIs with Python.
1. Create a FastAPI App
First, create a new FastAPI app using the FastAPI class.
from fastapi import FastAPI
app = FastAPI()
2. Define a Data Model
Next, define a data model using Pydantic. This will be used to define the structure and validation rules for the data.
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
is_active: bool = True
class Config:
orm_mode = True
3. Create Route for Creating Items
Create a route that handles POST requests to create new items.
@app.post("/items/")
async def create_item(item: Item):
# Add code to save the item to the database
return {"message": "Item created successfully"}
4. Create Route for Retrieving Items
Create a route that handles GET requests to retrieve items.
@app.get("/items/")
async def get_items():
# Add code to retrieve items from the database
return {"message": "Items retrieved successfully"}
5. Create Route for Updating Items
Create a route that handles PUT requests to update items.
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
# Add code to update the item in the database
return {"message": f"Item with ID {item_id} updated successfully"}
6. Create Route for Deleting Items
Create a route that handles DELETE requests to delete items.
@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
# Add code to delete the item from the database
return {"message": f"Item with ID {item_id} deleted successfully"}
7. Run the App
Finally, run the FastAPI app using the uvicorn command.
uvicorn main:app --reload
That's it! You now have a basic FastAPI app with CRUD operations.
Детальный ответ
FastAPI CRUD Example
Welcome to this article where we will explore an example of CRUD operations using FastAPI. FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It comes with various features that make it a powerful tool for developing API applications.
Before diving into the example, let's briefly understand what CRUD operations mean. CRUD stands for Create, Read, Update, and Delete. These are the basic operations that are performed on data in databases or any other storage systems. In this example, we will use FastAPI to create an API that can handle these CRUD operations.
Setting Up FastAPI
To get started, let's set up the FastAPI environment. First, make sure you have Python installed on your system. You can check by running the following command in your terminal:
python --version
If you don't have Python installed, you can download and install it from the official Python website.
Once you have Python installed, you can install FastAPI using pip, the Python package manager:
pip install fastapi
In addition, we will also need to install an ASGI (Asynchronous Server Gateway Interface) server to run our FastAPI application. In this example, we will use Uvicorn as the ASGI server:
pip install uvicorn
Creating the FastAPI Application
Now that we have FastAPI installed, let's create our FastAPI application. Create a new Python file called main.py and open it in your favorite text editor. Start by importing the necessary modules:
from fastapi import FastAPI
from pydantic import BaseModel
Next, let's create an instance of the FastAPI
class:
app = FastAPI()
For this example, we will be working with a simple in-memory database. Let's create a list to store our data:
db = []
Defining the Model
Before we proceed to define the routes for our CRUD operations, let's define the data model for our API. We will be using Pydantic, a library for data validation and parsing. Create a new Python file called models.py and open it in your text editor.
In this example, we will be working with a `User` model, which will have two properties: `id` and `name`.
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
This model will be used as the schema for our API routes.
CRUD Routes
Now, let's define our CRUD routes in the main.py file. Add the following code to your main.py
file:
from typing import List
from models import User
@app.post('/users/')
def create_user(user: User):
db.append(user)
return {'message': 'User created'}
@app.get('/users/')
def get_users():
return db
@app.get('/users/{user_id}')
def get_user(user_id: int):
for user in db:
if user.id == user_id:
return user
return {'message': 'User not found'}
@app.put('/users/{user_id}')
def update_user(user_id: int, updated_user: User):
for i, user in enumerate(db):
if user.id == user_id:
db[i] = updated_user
return {'message': 'User updated'}
return {'message': 'User not found'}
@app.delete('/users/{user_id}')
def delete_user(user_id: int):
for i, user in enumerate(db):
if user.id == user_id:
del db[i]
return {'message': 'User deleted'}
return {'message': 'User not found'}
In the above code, we define five routes:
create_user
: This route is used to create a new user. It takes aUser
object as input and appends it to thedb
list.get_users
: This route is used to get all users. It simply returns thedb
list.get_user
: This route is used to get a specific user by their ID. It loops through thedb
list and returns the user if found.update_user
: This route is used to update a specific user by their ID. It loops through thedb
list, finds the user, and updates it with the new data.delete_user
: This route is used to delete a specific user by their ID. It loops through thedb
list, finds the user, and removes it from the list.
Running the Application
With the routes defined, we can now run our FastAPI application. In your terminal, navigate to the directory where your main.py
file is located. Run the following command to start the ASGI server:
uvicorn main:app --reload
You should see output indicating that the ASGI server has started. By default, the server runs on http://localhost:8000
.
You can now test the CRUD operations using your favorite API testing tool (e.g., Postman).
Creating a User
To create a user, send a POST
request to http://localhost:8000/users
with the following JSON payload:
{
"id": 1,
"name": "John Doe"
}
Getting all Users
To get all users, send a GET
request to http://localhost:8000/users
. The API will return a JSON response containing the list of users.
Getting a User by ID
To get a specific user by their ID, send a GET
request to http://localhost:8000/users/{user_id}
, replacing {user_id}
with the ID of the user you want to retrieve.
Updating a User
To update a specific user by their ID, send a PUT
request to http://localhost:8000/users/{user_id}
, replacing {user_id}
with the ID of the user you want to update. Include the updated user data in the request body.
Deleting a User
To delete a specific user by their ID, send a DELETE
request to http://localhost:8000/users/{user_id}
, replacing {user_id}
with the ID of the user you want to delete.
That's it! You have successfully implemented a CRUD API using FastAPI. Feel free to experiment and further enhance this example to meet your specific requirements.