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:

1 Días
20 Hrs
22 Min
21 Seg

Documentación de APIs con Django REST, Swagger y OpenAPI

12/21
Resources

When we create an API, the main objective is that other systems or developers can integrate with our system in an efficient way. To achieve this, a clear and updated documentation is essential. Tools such as DRF Spectacular and Swagger make this task easier, automating the generation of documentation and allowing it to be always synchronized with our code.

How to document an API automatically?

  • Django and Django REST Framework (DRF) offer us the possibility of using a library called DRF Spectacular. This tool follows the OpenAPI standard to generate automatic documentation.
  • This standard allows any change in the views or API endpoints to be immediately reflected in the documentation, without the need to modify it manually.

What is Swagger and how to use it for your API documentation?

  • Swagger is a visual interface that displays the documentation generated by DRF Spectacular. It allows developers to interact directly with the API, test endpoints and review possible parameters and responses.
  • In addition, it offers the option to download an OpenAPI schema file that can be used by other tools or interfaces.

How to create the documentation application in Django?

  1. Create a new application called docs from the terminal.
    • Register this application in the Installed Apps list in the settings.py file.
  2. Install the DRF Spectacular library by executing the command pip install drf-spectacular.
    • Also register this library in the installed applications.
  3. Configure an automatic scheme in settings.py making sure there are no duplicates in the configuration.

How to add Swagger and Redoc URLs?

  • Inside the urls.py file of the docs application, add the URLs corresponding to Swagger and Redoc.
  • Don't forget to import correctly the paths with path from django.urls.
  • Add the URLs of the docs application to the main URL file of the project so that they are accessible.

What is the difference between Swagger and Redoc?

  • Swagger provides an interface where you can interact with the endpoints and test the responses without leaving the browser.
  • Redoc is another interface that allows you to navigate between endpoints in a more organized way, with a search engine and a list of available resources. It also shows details of possible responses and errors.

How to improve the documentation of each endpoint?

  • You can add descriptions to each of the endpoints in your view classes, using Python comments.
  • These comments will automatically appear in the Swagger or Redoc documentation, making it easier for other developers to understand the behavior of each resource.

What are the advantages of the OpenAPI standard?

  • OpenAPI allows any tool that follows this standard, such as Swagger or Redoc, to interpret the API schema and generate visual documentation.
  • It is a widely used format and compatible with different user interfaces.

How to update the documentation when modifying the code?

  • The main advantage of using DRF Spectacular is that when the code is modified, the documentation is automatically updated. This ensures that it is always synchronized and prevents you from having to edit the documentation manually.

Contributions 8

Questions 3

Sort by:

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

# Swagger es HERMOSO, lo use pila en el curso de FastAPI. Lo recomiendo a la n potencia.
Chicos, si algunos cuando entra a la api y ve toda la doc de las apis adjuntas, pues puede que les pase lo siguiente: deben quitar el indicardor de la api en `urls.py` de doctor app: ```js path("docs", include("docs.urls")) a path("", include("docs.urls")), ```con esto cuando vuelvan a entrar, pues les aparecerá la doc organizada!
Tanto Swager com Redoc se ven como buenas opciones para documentación. Aunque por gusto prefiero Redoc.
¿Como hago para mejorar la visualización de la documentación por cada entidad (clase)? Se ven todos los endpoints juntos: ![](https://static.platzi.com/media/user_upload/image-0d33d5c1-3c4b-4fec-b136-124dd08304e0.jpg)
Que buen curso este, no me lo imagine de esta forma, ya tiene sus 5 estrellas
Cinco ventajas de documentar una API: 1. **Facilita la comprensión**: Ayuda a los desarrolladores a entender cómo usar la API. 2. **Mejora la colaboración**: Permite que diferentes equipos trabajen juntos de manera más eficiente. 3. **Acelera el desarrollo**: Reduce el tiempo necesario para integrar y utilizar la API. 4. **Aumenta la calidad**: Ayuda a identificar y corregir errores más rápidamente. 5. **Promueve la adopción**: Hace que la API sea más atractiva y accesible para nuevos usuarios.
En **Django Rest Framework (DRF)** puedes usar **drf-spectacular** para generar documentación OpenAPI detallada y personalizada. Configúralo de la siguiente manera En settings de python SPECTACULAR\_SETTINGS = { 'TITLE': "Hospitals API's🏥", 'DESCRIPTION': 'Schedule your turn➕', 'VERSION': '0.0.1', 'SERVE\_INCLUDE\_SCHEMA': False, } Así se ve en web: ![](https://static.platzi.com/media/user_upload/image-dac056d3-75fe-4cc1-9f68-c136f3b0cdce.jpg)
Yo en mis proyectos con DRF siempre uso @personal\_appointment\_list\_by\_patient\_view\_schema()class PersonalAppointmentListByPatientView(BasePermissionAPIView):    permission\_classes = \[IsAuthenticated, PersonalAppointmentPermission]`drf-spectacular` documentado con decoradores de la siguiente manera: ```python # views.py from .schemas import personal_appointment_list_by_patient_view_schema @personal_appointment_list_by_patient_view_schema() class PersonalAppointmentListByPatientView(BasePermissionAPIView): permission_classes = [IsAuthenticated, PersonalAppointmentPermission] def get_patient(self, patient_id: int): pass def get_query_params(self, data): pass def get_query(self, data, query_search, patient_id): pass def get_personal_appointment(self, query): pass def get(self, request: Request, patient_id: int): pass ``` ```js # schemas.py from drf_spectacular.utils import ( OpenApiResponse, extend_schema, extend_schema_view, inline_serializer, ) def personal_appointment_list_by_patient_view_schema(): return extend_schema_view( get=extend_schema( operation_id="personal_appointment_list_by_patient", summary="Retrieve a list of personal appointments by patient", description="Retrieve a list of personal appointments by patient", tags=["Personal Appointment"], parameters=[PersonalAppointmentListSerializer], responses={ 200: OpenApiResponse( response=inline_serializer( name="PersonalAppointmentListByPatient", fields=schema_pagination_serializer(PersonalAppointmentDetailSerializer), ), description="List of personal appointments by patient", ), 400: OpenApiResponse( response=schema_error_400, description="Bad request", ), 404: OpenApiResponse( response=schema_error("Patient not found.", json_schema=True), description="Patient not found", ), }, ), ) ``` Con esto nos da más flexibilidad en crear la documentación y agregar loss métodos que estemos suando