56 lines
1.5 KiB
Markdown
56 lines
1.5 KiB
Markdown
---
|
||
title: "RESTful API设计"
|
||
type: concept
|
||
tags: [api, rest, django-rest-framework]
|
||
sources: [tiktok-pm-python-django-project.md]
|
||
last_updated: 2026-04-14
|
||
---
|
||
|
||
## Definition
|
||
RESTful API是一种基于HTTP协议的API设计风格,使用URL表示资源,使用HTTP方法表示操作。
|
||
|
||
## Implementation in TikTok PM
|
||
|
||
### ViewSet
|
||
使用Django REST Framework的ModelViewSet自动生成CRUD路由:
|
||
```python
|
||
class ProductViewSet(viewsets.ModelViewSet):
|
||
queryset = Product.objects.all()
|
||
serializer_class = ProductSerializer
|
||
```
|
||
|
||
### Router
|
||
使用DefaultRouter自动生成路由:
|
||
```python
|
||
router = DefaultRouter()
|
||
router.register(r'products', views.ProductViewSet)
|
||
```
|
||
|
||
### Serializers
|
||
序列化器将Django模型转换为JSON:
|
||
```python
|
||
class ProductSerializer(serializers.ModelSerializer):
|
||
images = ProductImageSerializer(many=True, read_only=True)
|
||
class Meta:
|
||
model = Product
|
||
exclude = ['raw_json', 'input']
|
||
```
|
||
|
||
### Filtering
|
||
启用django-filter进行多条件过滤:
|
||
```python
|
||
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
|
||
- [[RESTful API设计]] ← uses ← [[Django]]
|
||
- [[RESTful API设计]] ← integrated_with ← [[Django Admin定制]]
|
||
- [[RESTful API设计]] ← consumed_by ← [[n8n]]
|