You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

2 D铆as
2 Hrs
47 Min
38 Seg

Gesti贸n de Vistas Basadas en Funciones en Django REST Framework

7/21
Resources

The implementation of endpoints in Django REST Framework allows us to work with resources as patients, both to list them and to create them, using the appropriate HTTP methods. The next step will be to extend these functionalities to modify and delete records.

How to implement the creation of patients with POST on the same endpoint?

To allow both the creation and reading of patients on a single endpoint, we use GET and POST methods. GET takes care of listing patients, while POST creates a new one. To achieve this:

  • You check the method of the request (GET or POST) using request.method.
  • If GET, it continues to list the patients.
  • If it is POST, the information sent in the body of the request is validated through a serializer.
  • If the data is valid, the save() method is used to save the new patient in the database.

How are validation errors handled in POST?

In case the data sent is invalid, Django REST Framework catches the errors and formats them into a JSON response. This is done with raise_exception=True in the serializer, which automatically returns a response with the error details without the need for a conditional.

How to return a proper response when creating a resource?

Once the patient is successfully created, the server responds with an HTTP 201 status code, indicating that the resource was created. This is done with Response(status=status.HTTP_201_CREATED), ensuring that the client receives the appropriate confirmation.

How to display the detail of a patient with GET?

To get the detail of a specific patient, you use the GET method on an endpoint that includes a URL parameter, usually the patient ID:

  • You filter the patient by ID with get_object_or_404().
  • If the patient exists, its information is returned in JSON format.
  • If it does not exist, a 404 status code is returned.

How to handle the modification of a patient with PUT?

The PUT method allows you to modify an existing patient. It uses the same logic as GET to obtain the patient, but instead of returning the data, it updates the information received:

  • It checks if the method is PUT.
  • The patient data is validated with a serializer.
  • If the data is valid, the update is saved and a 200 code is returned indicating success.

Contributions 12

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

Dejo la funci贸n PUT: ```python @api_view(["PUT"]) def update_patient(request, pk): try: # Look for the patient by their primary key (pk) patient = Patient.objects.get(pk=pk) except Patient.DoesNotExist: # If the patient does not exist, return a 404 error return Response({'error': 'Patient not found'}, status=status.HTTP_404_NOT_FOUND) # Deserialize the incoming request data serializer = PatientSerializer(patient, data=request.data) # Validate the incoming data if serializer.is_valid(): # Save the changes if the data is valid serializer.save() # Return the updated patient data return Response(serializer.data) # If the data is not valid, return the errors return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ```
```python patient_exits = Patient.objects.filter( first_name=request.data['first_name'], last_name=request.data['last_name'], date_of_birth=request.data['date_of_birth'] ) ```
Este c贸digo me qued贸 c贸modo pero prueben ustedes qu茅 les parece: ```js # Importaciones necesarias from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .models import Patient # Importar el modelo Patient from .serializers import PatientSerializer # Importar el serializer del modelo # 1. M茅todo GET: Obtener todos los pacientes @api_view(["GET"]) def list_patients(request): patients = Patient.objects.all() # Obtener todos los pacientes serializer = PatientSerializer(patients, many=True) # Serializar los datos return Response(serializer.data) # Devolver los datos en formato JSON # 2. M茅todo POST: Crear un nuevo paciente @api_view(["POST"]) def create_patient(request): serializer = PatientSerializer(data=request.data) # Deserializar los datos del cliente if serializer.is_valid(): # Validar los datos serializer.save() # Guardar el nuevo paciente return Response(serializer.data, status=status.HTTP_201_CREATED) # Respuesta exitosa return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # Devolver errores si los datos no son v谩lidos # 3. M茅todo PUT: Actualizar un paciente existente @api_view(["PUT"]) def update_patient(request, pk): try: patient = Patient.objects.get(pk=pk) # Obtener el paciente por su ID (pk) except Patient.DoesNotExist: return Response({'error': 'Paciente no encontrado'}, status=status.HTTP_404_NOT_FOUND) serializer = PatientSerializer(patient, data=request.data) # Deserializar y actualizar con los nuevos datos if serializer.is_valid(): serializer.save() # Guardar los cambios return Response(serializer.data) # Respuesta con los datos actualizados return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # Devolver errores si los datos no son v谩lidos # 4. M茅todo DELETE: Eliminar un paciente @api_view(["DELETE"]) def delete_patient(request, pk): try: patient = Patient.objects.get(pk=pk) # Obtener el paciente por su ID (pk) except Patient.DoesNotExist: return Response({'error': 'Paciente no encontrado'}, status=status.HTTP_404_NOT_FOUND) patient.delete() # Eliminar el paciente return Response({'message': 'Paciente eliminado correctamente'}, status=status.HTTP_204_NO_CONTENT) ```
```python @api_view(['GET','PUT']) def patient_detail_view(request, id): if request.method == 'GET': patient = Patient.objects.filter(id=id).first() if patient is None: return Response(status=status.HTTP_404_NOT_FOUND) serializer = PatientSerializer(patient) return Response(serializer.data) if request.method == 'PUT': patient = Patient.objects.filter(id=id).first() if patient is None: return Response(status=status.HTTP_400_BAD_REQUEST) serializer = PatientSerializer(patient, data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) ```
Mi soluci贸n al reto:@api\_view(\["GET", "PUT"])def patient(request, pk, format=None): match request.method: case "GET": data = None status = HTTP\_200\_OK try: patient = Patient.objects.get(id=pk) serializer = PatientSerializer(patient) data = serializer.data except Patient.DoesNotExist: data = {"error": "Patient not found"} status = HTTP\_404\_NOT\_FOUND finally: return Response(data, status=status) case "PUT": data = None status = HTTP\_200\_OK try: patient = Patient.objects.get(id=pk) serializer = PatientSerializer(patient, data=request.data, partial=True) serializer.is\_valid(raise\_exception=True) serializer.save() data = serializer.data except Patient.DoesNotExist: data = {"error": "Patient not found"} status = HTTP\_404\_NOT\_FOUND finally: return Response(data, status=status) ```python @api_view(["GET", "PUT"]) def patient(request, pk, format=None): match request.method: case "GET": data = None status = HTTP_200_OK try: patient = Patient.objects.get(id=pk) serializer = PatientSerializer(patient) data = serializer.data except Patient.DoesNotExist: data = {"error": "Patient not found"} status = HTTP_404_NOT_FOUND finally: return Response(data, status=status) case "PUT": data = None status = HTTP_200_OK try: patient = Patient.objects.get(id=pk) serializer = PatientSerializer(patient, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() data = serializer.data except Patient.DoesNotExist: data = {"error": "Patient not found"} status = HTTP_404_NOT_FOUND finally: return Response(data, status=status) ```
importante si cuando usando el metodo 'PUT' solo le mandan un campo, por ejemplo:patient\_serializer = PatientSerializer(patient, data=request.data, partial=True) ```js {"first_name": "Nuevo Nombre"} ```van a recibir error, porque los serializers de django siempre espera que lleguen todos los campos segun las condiciones en la que se hayan creado sus campos, en este caso similar al Modelo, porque usamos ModelSerializer, asi que para actualizer un atributo o varios de forma parcial deben usar el serializer asi: ```python patient_serializer = PatientSerializer(patient, data=request.data, partial=True) ```y si sera valido, de caso contrario no lo es.
`patient_exits = Patient.objects.filter(聽 聽 聽 聽 聽 聽 聽 聽 first_name=request.data['first_name'],聽 聽 聽 聽 聽 聽 聽 聽 last_name=request.data['last_name'],聽 聽 聽 聽 聽 聽 聽 聽 date_of_birth=request.data['date_of_birth']聽 聽 聽 聽 聽 聽 )聽 聽 聽 聽 聽 聽 if patient_exits:聽 聽 聽 聽 聽 聽 聽 聽 return Response({'message': 'Patient already exists'}, status=status.HTTP_400_BAD_REQUEST)`
No estoy tan acostumbrado de escribir c贸digo as铆, o por lo menos el backend, si no tener una api por cada operaci贸n, pero lo simpliqu茅 a ver como se ve con python, no se nada mal: ```js @api_view(["GET", "PUT", "DELETE"]) def onePatient(request, id): try: patient = Patient.objects.get(id=id) if request.method == "GET": serializer = PatientSerializer(patient) return Response(serializer.data, status=status.HTTP_200_OK) elif request.method == "PUT": serializer = PatientSerializer(patient, data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) elif request.method == "DELETE": patient.delete() return Response( {"message": "Patient deleted"}, status=status.HTTP_204_NO_CONTENT ) except Patient.DoesNotExist: return Response( {"message": "Patient not found"}, status=status.HTTP_404_NOT_FOUND ) ```
**PUT** ```python # modificar un paciente if request.method == 'PUT': try: patient = Patient.objects.get(pk=pk) except Patient.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = PatientSerializer(patient, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ```
Entre los c贸digos HTTP m谩s comunes se encuentran el 200 (OK), que indica que la solicitud ha sido exitosa; el 404 (Not Found), que se帽ala que el recurso solicitado no se ha encontrado; el 500 (Internal Server Error), que indica un error en el servidor; el 301 (Moved Permanently), que informa que el recurso ha sido movido de forma permanente a una nueva URL; y el 302 (Found), que se帽ala una redirecci贸n temporal. Estos c贸digos ayudan a diagnosticar y solucionar problemas en la navegaci贸n web, asegurando una experiencia m谩s fluida para los usuarios.
Put: ![](https://static.platzi.com/media/user_upload/code-21bb39bb-9634-44ab-b2e2-7d8fec6ba8eb.jpg)
@api\_view(\["GET", "POST"])def list\_patients(request): if request.method == "GET": patients = Patient.objects.all() serializer = PatientSerializer(patients, many=True) return Response(serializer.data, status=status.HTTP\_200\_OK) elif request.method == "POST": serializer = PatientSerializer(data=request.data) if serializer.is\_valid(): serializer.save() return Response(serializer.data, status=status.HTTP\_201\_CREATED) else: return Response(serializer.errors, status=status.HTTP\_400\_BAD\_REQUEST)