D
< < <{
"data": [
{
"id": 1,
"email": "bobmarley@gmail.com",
}
],
"error": {}
}
<
{
"data": [],
"error": {
"email": [
"This field is required."
]
}
}
<
{
"data": [],
"error": {
"non_field_errors": [
"Description of the error."
]
}
}
<
<
/clients:
post:
summary: Create New Client
operationId: post-clients
responses:
'200':
description: Client Created
content:
application/json:
schema:
$ref: '#/components/schemas/Result'
examples: {}
'400':
description: Missing Required Information
'409':
description: Email Already Taken
<
{
"data": [],
"error": {
"non_field_errors": [
"{'email': [ErrorDetail(string='person with this email already exists.', code='unique')]}"
]
}
}
<
class Client(models.Model):
id = models.AutoField(primary_key=True)
email = models.EmailField(unique=True)
class Meta:
db_table = "clients"
def __str__(self):
return self.email
<
class ClientSerializer(serializers.ModelSerializer):
class Meta:
model = Client
<
class ClientView(APIView):
def post(self, request):
data = []
error = {}
result = {"data": data, "error": error}
try:
client_serializer = ClientSerializer(data=request.data)
client_serializer.is_valid(raise_exception=True)
client_serializer.save()
data.append(client_serializer.data)
return Response(result, status=status.HTTP_201_CREATED)
except Exception as err:
error['non_field_errors'] = [str(err)]
return Response(result, status=status.HTTP_200_OK)
это зависит от вашей стороны
{
"data": [],
"error": {
"email": [
"This field is required."
]
}
}
Я должен сказать, что это иногда неправильно, потому что ошибки могут быть разными, я имею в виду, что могут быть валидации строк, проверка на основе страны или другие.
Я предлагаю такой код
{
"data": [],
"error": {
"non_field_errors": [
{'email': [ErrorDetail(string='person with this email already exists.', code='unique')]}
]
}
}
В другом случае вы можете получить ошибки и вручную отправить их на сторону клиента, например:
client_serializer = ClientSerializer(data=request.data)
if client_serializer.is_valid():
return client_serializer.save()
else:
return {"errors": client_serializer.errors}
Вы можете возвращать данные ответа по своему усмотрению.
class ClientView(APIView):
def post(self, request):
data = []
error = {}
result = {"data": data, "error": error}
try:
client_serializer = ClientSerializer(data=request.data)
if not client_serializer.is_valid():
result["error"] = client_serializer.errors
return Response(result, status=status.HTTP_400_BAD_REQUEST)
client_serializer.save()
data.append(client_serializer.data)
result["data"] = data
return Response(result, status=status.HTTP_201_CREATED)
except Exception as err:
result["data"] = []
result["error"] = "Something went wrong"
return Response(result, status=status.HTTP_200_OK)