Axios与FastAPI结合:构建并请求用户增删改查接口

在现代Web开发中,FastAPI以其高性能和简洁的代码结构成为了构建RESTful API的热门选择。而Axios则因其基于Promise的HTTP客户端特性,成为了前端与后端交互的理想工具。本文将介绍FastAPI和Axios的结合使用,通过一个用户增删改查(CRUD)接口的实例,展示如何构建和请求API。

FastAPI简介

FastAPI是一个现代、快速的Web框架,用于构建API。它基于Python 3.6+类型提示,结合了Pydantic和Starlette的功能,提供了数据验证和序列化。FastAPI的核心优势在于其高性能、易用性、自动化文档生成以及对现代Python编程实践的深度支持。

Axios简介

Axios是一个基于Promise的HTTP客户端,广泛用于浏览器和Node.js环境。它以其简洁的API和强大的功能,成为了现代Web开发中不可或缺的工具。Axios的核心特性包括从浏览器创建XMLHttpRequests、从Node.js创建http请求、支持Promise API、拦截请求和响应、转换请求和响应数据、取消请求等。

FastAPI开发用户CRUD接口案例

以下是一个使用FastAPI和SQLModel实现用户CRUD操作的简单案例:

1. 安装依赖

首先,确保安装了FastAPI和SQLModel:

复制代码
pip install fastapi uvicorn sqlmodel

2. 定义模型

models.py中定义用户模型:

复制代码
from sqlmodel import SQLModel, Field

class UserBase(SQLModel):
    name: str
    age: int = Field(default=None, nullable=True)

class User(UserBase, table=True):
    id: int = Field(default=None, primary_key=True)

3. 创建数据库引擎

database.py中设置数据库连接和表:

复制代码
from sqlmodel import create_engine

DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(DATABASE_URL)

4. 实现CRUD操作

crud.py中实现CRUD操作:

复制代码
from models import User
from database import engine
from sqlmodel import Session, select

def get_user(user_id: int):
    stmt = select(User).where(User.id == user_id)
    with Session(engine) as session:
        return session.exec(stmt).first()

def create_user(user: User):
    with Session(engine) as session:
        session.add(user)
        session.commit()
        session.refresh(user)
        return user

def update_user(user_id: int, user: User):
    user.id = user_id
    with Session(engine) as session:
        session.add(user)
        session.commit()
        session.refresh(user)
        return user

def delete_user(user_id: int):
    user = get_user(user_id)
    if user:
        with Session(engine) as session:
            session.delete(user)
            session.commit()
            return True
    return False

5. 创建API端点

main.py中创建API端点:

复制代码
from fastapi import FastAPI, HTTPException, Depends
from database import engine
from crud import create_user, get_user, update_user, delete_user
from models import User

app = FastAPI()

@app.on_event("startup")
def on_startup():
    SQLModel.metadata.create_all(engine)

@app.post("/users/", response_model=User)
def create_user_endpoint(user: User):
    return create_user(user)

@app.get("/users/{user_id}", response_model=User)
def read_user(user_id: int):
    user = get_user(user_id)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user

@app.put("/users/{user_id}", response_model=User)
def update_user_endpoint(user_id: int, user: User):
    user.id = user_id
    updated_user = update_user(user_id, user)
    if not updated_user:
        raise HTTPException(status_code=404, detail="User not found")
    return updated_user

@app.delete("/users/{user_id}", response_class=HTTPException)
def delete_user_endpoint(user_id: int):
    if not delete_user(user_id):
        raise HTTPException(status_code=404, detail="User not found")
    return {"detail": "User deleted"}

使用Axios请求FastAPI接口

1. 安装Axios

在项目中安装Axios:

复制代码
npm install axios

2. 请求用户数据

获取用户列表
复制代码
axios.get('http://localhost:8000/users')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error fetching users:', error);
  });
创建新用户
复制代码
axios.post('http://localhost:8000/users', {
  name: 'John Doe',
  age: 30
})
.then(response => {
  console.log(response.data);
})
.catch(error => {
  console.error('Error creating user:', error);
});
更新用户信息
复制代码
axios.put('http://localhost:8000/users/1', {
  name: 'John Doe Updated',
  age: 31
})
.then(response => {
  console.log(response.data);
})
.catch(error => {
  console.error('Error updating user:', error);
});
删除用户
复制代码
axios.delete('http://localhost:8000/users/1')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error deleting user:', error);
  });

结论

FastAPI和Axios的结合为现代Web应用开发提供了一个强大而灵活的平台。FastAPI的高性能和易用性,结合Axios的简洁API和强大的HTTP客户端功能,使得从后端到前端的整个开发流程变得更加高效和可靠。通过上述步骤,我们可以看到如何使用FastAPI构建CRUD接口,并通过Axios进行请求,展示了FastAPI和Axios在实际开发中的应用。

相关推荐
卷无止境1 天前
Linux + Docker + FastAPI 工程化实践指南
后端·python·fastapi
皮卡丘不断更2 天前
手机优先的 Personal Ledger:把账目、学习和复盘放到同一个入口
数据库·sqlite·fastapi·开源项目·个人效率
智购科技自动售卖机厂家2 天前
2026自动售货机OTA升级系统设计:从全量升级到差分升级的带宽优化工程实践~YH
大数据·人工智能·numpy·pyqt·fastapi
Broccoli523026652 天前
FastAPI 中间件
中间件·fastapi
刘新洲3 天前
我以为 AI Agent 只是调模型,直到我亲手补上审批、Outbox 和故障恢复
python·agent·fastapi
(((φ(◎ロ◎;)φ)))牵丝戏安3 天前
fastapi-auth-template — JWT 认证模板
运维·服务器·fastapi
l1258653 天前
# RAG多轮对话检索设计:Query重写如何让“那它呢“变成完整问题
前端·数据库·人工智能·python·算法·fastapi·milvus
赵广陆5 天前
企业实战:web服务集成
前端·pycharm·fastapi
雪碧聊技术5 天前
使用Docker,将fastApi项目部署到linux服务器
服务器·docker·fastapi·docker部署fastapi
丑过三八线5 天前
002 - 【FastAPI 入门教程】请求体与数据校验
fastapi