《每天5分钟用Flask搭建一个管理系统》第9章:API设计

第9章:API设计

9.1 RESTful API的概念

RESTful API是一种基于HTTP协议的网络服务接口设计方法,它使用标准的HTTP方法,如GET、POST、PUT、DELETE等,来执行资源的操作。

9.2 Flask-RESTful扩展的使用

Flask-RESTful是一个Flask扩展,简化了创建RESTful API的过程。

示例代码:安装Flask-RESTful

bash 复制代码
pip install flask-restful

示例代码:创建API资源

python 复制代码
from flask import Flask
from flask_restful import Api, Resource, reqparse

app = Flask(__name__)
api = Api(app)

class HelloWorld(Resource):
    def get(self):
        return {'hello': 'world'}

api.add_resource(HelloWorld, '/')
9.3 API路由和视图的创建

在Flask-RESTful中,资源(Resource)是API的基本单元,每个资源都映射到一个URL路由。

示例代码:添加资源到API

python 复制代码
class UserResource(Resource):
    def get(self, user_id):
        # 假设有一个函数get_user可以获取用户数据
        return get_user(user_id)

api.add_resource(UserResource, '/users/<int:user_id>')
9.4 数据序列化和反序列化

序列化是将数据结构或对象状态转换为可存储或可传输的格式的过程。反序列化是序列化相反的过程。

示例代码:使用Marshmallow序列化数据

bash 复制代码
pip install marshmallow
python 复制代码
from marshmallow import Schema, fields

class UserSchema(Schema):
    id = fields.Int()
    username = fields.Str()
    email = fields.Email()

user_schema = UserSchema()

# 序列化
data, errors = user_schema.dump(user)
# 反序列化
data, errors = user_schema.load(request.json)
9.5 API输入验证

在API开发中,验证输入数据的正确性是非常重要的。

示例代码:使用Marshmallow进行输入验证

python 复制代码
class UserSchema(Schema):
    username = fields.Str(required=True)
    email = fields.Email(required=True)

user_schema = UserSchema()

# 验证输入
result = user_schema.load(request.json)
if result.errors:
    # 处理错误
9.6 API的错误处理

在API设计中,合理的错误处理可以提供清晰的错误信息,帮助客户端开发者理解问题所在。

示例代码:自定义错误处理

python 复制代码
from flask_restful import Resource, Api, reqparse, abort

class UserResource(Resource):
    def get(self, user_id):
        if user_id == 'invalid':
            abort(404, message="User not found")
        return {'user_id': user_id}

api.add_resource(UserResource, '/users/<string:user_id>')
9.7 总结

本章介绍了RESTful API的概念,以及如何使用Flask-RESTful和Marshmallow扩展来创建API资源、序列化和反序列化数据、进行输入验证和错误处理。

相关推荐
盼小辉丶17 分钟前
OpenCV-Python实战——分析与加速OpenCV应用程序
python·神经网络·opencv·计算机视觉
用户2986985301424 分钟前
Java 创建 CSV 文件的三种实用方法:从零构建、数组写入与 Excel 转换
java·后端·excel
buhuizhiyuci26 分钟前
【python篇——一周速通python语法】python的条件语句和循环语句
开发语言·python
玉宇夕落29 分钟前
Cheerio虚拟DOM原理
后端
geovindu30 分钟前
go: Recursion Algorithm
开发语言·后端·算法·golang·递归算法
用户29307509766934 分钟前
深入理解 RAG 文档切割:从知识库到向量数据库的关键一步
后端
geovindu36 分钟前
CSharp: Composite Pattern
开发语言·后端·c#·组合模式·结构型模式
学AI不秃头37 分钟前
官方要 16GB,实测 4-bit 压到 2.9GB:把 LocateAnything-3B 搬上 8GB Jetson
python·深度学习·机器学习·计算机视觉·机器人
宇图SHARE43 分钟前
别再用 Python 写 Agent 前端了!Vue3 + NestJS + TypeScript 全栈方案,开发效率翻倍
前端·后端
吃饱了得干活1 小时前
Spring Cloud Gateway限流:从Redis到Sentinel的三种方案
后端·spring cloud