Files
nexus/wiki/concepts/RESTful-API设计.md
2026-04-14 16:02:50 +08:00

1.5 KiB
Raw Blame History

title, type, tags, sources, last_updated
title type tags sources last_updated
RESTful API设计 concept
api
rest
django-rest-framework
tiktok-pm-python-django-project.md
2026-04-14

Definition

RESTful API是一种基于HTTP协议的API设计风格使用URL表示资源使用HTTP方法表示操作。

Implementation in TikTok PM

ViewSet

使用Django REST Framework的ModelViewSet自动生成CRUD路由

class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

Router

使用DefaultRouter自动生成路由

router = DefaultRouter()
router.register(r'products', views.ProductViewSet)

Serializers

序列化器将Django模型转换为JSON

class ProductSerializer(serializers.ModelSerializer):
    images = ProductImageSerializer(many=True, read_only=True)
    class Meta:
        model = Product
        exclude = ['raw_json', 'input']

Filtering

启用django-filter进行多条件过滤

filter_backends = [DjangoFilterBackend, filters.SearchFilter]
filterset_fields = ['available', 'category', 'seller_id', 'final_price']

API Routes

  • GET /api/products/:查询所有产品
  • GET /api/products/?search=关键词:关键词搜索
  • GET /api/products/?category=服饰&In_stock=true多条件过滤
  • POST /api/products/:创建产品

Connections