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

56 lines
1.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
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]]