De 0 a Django REST
Miguel Jiménez
2
Objetivos
Pasos Previos
4
Pasos Previos
5
Contenido
Conceptos Básicos
Inicializar proyecto
Requests
1
2
3
Instalar Django y módulos, Iniciar el proyecto, Estructura Django, Modelos
API REST, Python, Django, Django REST Framework
GET, POST, PUT/PATCH, DELETE
6
Conceptos Básicos
API REST, Python, Django, Django REST Framework
1. API REST
Interfaz para gestionar recursos de un sistema
https://es.wikipedia.org/wiki/Transferencia_de_Estado_Representacional
2. Python
2. Python
import json
from django.urls import path
urlpatterns = [1,2]
def get_things(thing):
return thing
class Car():
colour = red
3. Django
4. Django REST Framework
Inicializar Proyecto
Instalar Django y módulos, Iniciar el proyecto, Estructura Django, Modelos
Repositorio
14
Repositorio
15
Crear Virtualenv e Instalar Módulos
1º) virtualenv .
2º) source bin/activate
16
S1
Crear Virtualenv e Instalar Módulos
3º) Crear archivo requirements.pip con:
Django==3.0.1
djangorestframework==3.10.3
ipdb==0.11
4º) pip install -r requirements.pip
17
S1
Iniciar Proyecto
1º) django-admin startproject De0aDjangoREST
2º) Entramos en la carpeta del proyecto De0aDjangoREST
18
S2
Iniciar App
Ya en la carpeta del proyecto introducimos:
python manage.py startapp cars
19
S3
Iniciar App
20
S3
Configurar Settings y URLs
Abrir De0aDjangoREST/settings.py
INSTALLED_APPS = [
...
'rest_framework',
'cars',
]
21
S4
Configurar Settings y URLs
Seguimos en De0aDjangoREST/settings.py y añadimos al final...
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
22
S4
Configurar Settings y URLs
Abrir De0aDjangoREST/urls.py
from django.urls import path
from django.conf.urls import include
urlpatterns = [
path('v1/cars/', include(cars.urls'))
]
23
S4
Configurar Settings y URLs
Crear cars/urls.py y añadir:
from django.urls import path
urlpatterns = [
]
24
S4
Iniciar Servidor
25
Estructura Django
MVC -> MVT
26
Estructura Django
En Django REST se podría decir que es así
27
Ficheros Django REST
Models: Representación de la información
Views: Gestiona el flujo de información
Serializers: Define cómo se van a mostrar los datos al cliente
Urls: Definición de las direcciones web y a que vista acceden
28
Modelo y Migraciones
En el archivo cars/models.py:
class Brand(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
name = models.CharField(max_length=15)
https://docs.djangoproject.com/en/3.0/ref/models/fields/
29
S5
Modelo y Migraciones
python manage.py makemigrations
python manage.py migrate
30
S5
Requests
GET, POST, PUT/PATCH, DELETE
GET
Obtener recursos
1º) Definimos el Serializador en cars/serializers.py
from rest_framework import serializers
from .models import Brand
class BrandSerializer(serializers.ModelSerializer):
class Meta:
model = Brand
fields = ('id', 'name’, )
32
S6
GET
Obtener recursos
2º) Definimos la Vista en cars/views.py
from rest_framework.generics import ListAPIView
from .models import Brand
from .serializers import BrandSerializer
class BrandListView(ListAPIView):
serializer_class = BrandSerializer
permission_classes = ()
queryset = Brand.objects.all()
33
S6
GET
Obtener recursos
3º) Definimos URL en cars/urls.py
from django.urls import path
from .views import BrandListView
urlpatterns = [
path('brands/', BrandListView.as_view(), name='brands'),
]
34
S6
GET
35
S6
POST
Crear un recurso
1º) Definimos Serializador en cars/serializers.py
36
S7
POST
Crear un recurso
2º) Definimos Vista en cars/views.py
from rest_framework.generics import CreateAPIView, ListAPIView
...
class BrandCreateView(CreateAPIView):
serializer_class = BrandSerializer
permission_classes = ()
37
S7
POST
Crear un recurso
3º) Definimos URL en cars/urls.py
from django.urls import path
from .views import BrandCreateView, BrandListView
urlpatterns = [
path('brands/', BrandListView.as_view(), name='brands'),
path('brands/create/', BrandCreateView.as_view(), name='brand_create'),
]
38
S7
POST
39
S7
GET
Obtener un recurso
1º) Definimos Vista en cars/views.py
from rest_framework.generics import (CreateAPIView, ListAPIView,
RetrieveAPIView)
...
class BrandRetrieveView(RetrieveAPIView):
serializer_class = BrandSerializer
permission_classes = ()
queryset = Brand.objects.all()
lookup_field = 'id'
40
S8
GET
Obtener un recurso
2º) Definimos URL en cars/urls.py
from django.urls import path
from .views import BrandCreateView, BrandListView, BrandRetrieveView
urlpatterns = [
path('brands/', BrandListView.as_view(), name='brands'),
path('brands/create/', BrandCreateView.as_view(), name='brand_create'),
path('brands/<int:id>/', BrandRetrieveView.as_view(), name='brand'),
]
41
S8
GET
42
S8
PUT/PATCH
Editar un recurso
1º) Definimos Vista en cars/views.py
from rest_framework.generics import (CreateAPIView, ListAPIView,
RetrieveAPIView, UpdateAPIView)
...
class BrandUpdateView(UpdateAPIView):
serializer_class = BrandSerializer
permission_classes = ()
queryset = Brand.objects.all()
lookup_field = 'id'
43
S9
PUT/PATCH
Editar un recurso
2º) Definimos URL en cars/urls.py
...
from .views import (BrandCreateView, BrandListView,
BrandRetrieveView, BrandUpdateView)
urlpatterns = [
...
path('brands/<int:id>/update/', BrandUpdateView.as_view(), name='brand_update'),
]
44
S9
PUT/PATCH
45
S9
DELETE
Eliminar un recurso
1º) Definimos Vista en cars/views.py
from rest_framework.generics import (CreateAPIView, DestroyAPIView, ListAPIView,
RetrieveAPIView, UpdateAPIView)
…
class BrandDestroyView(DestroyAPIView):
permission_classes = ()
queryset = Brand.objects.all()
lookup_field = 'id'
46
S10
DELETE
Eliminar un recurso
2º) Definimos URL en cars/urls.py
...
from .views import (BrandCreateView, BrandDestroyView, BrandListView,
BrandRetrieveView, BrandUpdateView)
urlpatterns = [
...
path('brands/<int:id>/delete/', BrandDestroyView.as_view(), name='brand_delete'),
]
47
S10
DELETE
48
S10
Next Steps
49