1 of 50

De 0 a Django REST

2 of 50

Miguel Jiménez

2

3 of 50

Objetivos

4 of 50

Pasos Previos

  • ¿Tienes un ordenador?

  • ¿Tienes Python instalado?

  • ¿Tienes VirtualEnv instalado?

  • ¿Tienes un cliente http como postman instalado?

4

5 of 50

Pasos Previos

  • ¿Problemas en windows?

https://bit.ly/38LURTW

5

6 of 50

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

7 of 50

Conceptos Básicos

API REST, Python, Django, Django REST Framework

8 of 50

1. API REST

Interfaz para gestionar recursos de un sistema

https://es.wikipedia.org/wiki/Transferencia_de_Estado_Representacional

9 of 50

2. Python

Lenguaje de programación

https://www.python.org/

10 of 50

2. Python

import json

from django.urls import path

urlpatterns = [1,2]

def get_things(thing):

return thing

class Car():

colour = red

11 of 50

3. Django

Framework web de alto nivel para Python

https://www.djangoproject.com

12 of 50

4. Django REST Framework

El módulo para desarrollar API RESTs con Django

https://www.django-rest-framework.org/

13 of 50

Inicializar Proyecto

Instalar Django y módulos, Iniciar el proyecto, Estructura Django, Modelos

14 of 50

Repositorio

14

15 of 50

Repositorio

15

16 of 50

Crear Virtualenv e Instalar Módulos

1º) virtualenv .

2º) source bin/activate

16

S1

17 of 50

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

18 of 50

Iniciar Proyecto

1º) django-admin startproject De0aDjangoREST

2º) Entramos en la carpeta del proyecto De0aDjangoREST

18

S2

19 of 50

Iniciar App

Ya en la carpeta del proyecto introducimos:

python manage.py startapp cars

19

S3

20 of 50

Iniciar App

20

S3

21 of 50

Configurar Settings y URLs

Abrir De0aDjangoREST/settings.py

INSTALLED_APPS = [

...

'rest_framework',

'cars',

]

21

S4

22 of 50

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

23 of 50

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

24 of 50

Configurar Settings y URLs

Crear cars/urls.py y añadir:

from django.urls import path

urlpatterns = [

]

24

S4

25 of 50

Iniciar Servidor

python manage.py runserver

Entramos en el navegador en http://127.0.0.1:8000/

Y si todo está bien….

25

26 of 50

Estructura Django

MVC -> MVT

26

27 of 50

Estructura Django

En Django REST se podría decir que es así

27

28 of 50

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

29 of 50

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

30 of 50

Modelo y Migraciones

python manage.py makemigrations

python manage.py migrate

30

S5

31 of 50

Requests

GET, POST, PUT/PATCH, DELETE

32 of 50

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

33 of 50

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

34 of 50

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

35 of 50

GET

Obtener recursos

http://127.0.0.1:8000/v1/cars/brands/

35

S6

36 of 50

POST

Crear un recurso

1º) Definimos Serializador en cars/serializers.py

36

S7

37 of 50

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

38 of 50

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

39 of 50

POST

Crear un recurso

http://127.0.0.1:8000/v1/cars/brands/create/

39

S7

40 of 50

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

41 of 50

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

42 of 50

GET

42

S8

43 of 50

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

44 of 50

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

45 of 50

PUT/PATCH

45

S9

46 of 50

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

47 of 50

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

48 of 50

DELETE

48

S10

49 of 50

Next Steps

49

50 of 50

Thanks!

50