En este tutorial aprenderas a crear tu primer REST API sencilla usando Django REST Framework y luego la desplegaras en un servicio llamado render.com que posee planes gratuitos.
Crear proyecto de Django REST Framework
mkdir drf_simple_crud
python3 -m virtualenv venv
pip install django djangorestframework
Iniciando proyecto Django
django-admin startproject drfsimplecrud .
python manage.py startapp projects
Añade los modulos
Luego actualiza el archivo settings.py
para añadir la apliacion Nueva:
INSTALLED_APPS = [
'projects',
'rest_framework',
]
Añadiendo Modelo de Tareas
En el archivo projects/models.py
actualiza el codigo a lo siguiente:
from django.db import models
# Create your models here.
class Project(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
technology = models.CharField(max_length=200)
created_at = models.DateTimeField(auto_now_add=True)
python manage.py makemigrations
python manage.py migrate
Creando Serializers
Los serializers nos permiten convertir estructura de datos de python a json:
ve en projects/serializers.py
from rest_framework import serializers
from .models import Project
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = ('id', 'title', 'description', 'technology', 'created_at')
read_only_fields = ('created_at',)
o puedes decirle todos:
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = '__all__'
read_only_fields = ('created_at',)
Creando un ViewSet
crea en projects/api.py
:
from projects.models import Project
from rest_framework import viewsets, permissions
from .serializers import ProjectSerializer
class ProjectViewSet(viewsets.ModelViewSet):
queryset = Project.objects.all()
permission_classes = [permissions.AllowAny]
serializer_class = ProjectSerializer
include
Luego vamos a incluir las rutas en el archivo drf_simple_crud/urls.py
:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('projects.urls'))
]
en projects/urls.py
:
from rest_framework import routers
from .api import ProjectViewSet
router = routers.DefaultRouter()
router.register('api/projects', ProjectViewSet, 'projects')
urlpatterns = router.urls
run server
python manage.py runserver
Probando API
### get all projects
GET http://localhost:8000/api/projects
### POST new project
POST http://localhost:8000/api/projects/
Content-Type: application/json
{
"title": "Frontend project",
"description": "New frontend project using React",
"technology": "Nextjs"
}
### GET project by id
GET http://localhost:8000/api/projects/1
### DELETE project by id
DELETE http://localhost:8000/api/projects/1/
### PATCH project by id
PATCH http://localhost:8000/api/projects/2/
Content-Type: application/json
{
"title": "E-commerce website react"
}
### PUT project by id
PUT http://localhost:8000/api/projects/2/
Content-Type: application/json
{
"title": "E-commerce website react",
"description": "New frontend project using React",
"technology": "Nextjs"
}