En este tutorial vamos a aprender a crear una API REST CRUD usando Django Rest Framework y la base de datos PostgreSQL. Crearemos una API REST que desarrolle las peticiones CRUD (Create, Read, Update, Delete) usando el Framework Backend de Python Django.
1 – Crear entorno virtual
python -m venv venv
Activar
#windows venv\Scripts\activate.bat .\venv\Scripts\activate.bat #linux or mac source venv/bin/activate
2 – Instalar Django
pip install django djangorestframework
3 – Iniciar proyecto
django-admin startproject tutofox cd tutofox
4 – Instalar PostgreSQL
pip install psycopg2
Configurar conexión
tutofox\settings.py
... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'tutofox', 'USER': 'postgres', 'PASSWORD': '12345', 'HOST': 'localhost', 'PORT': '5432', } } ...
5 – Migrate
python manage.py migrate
6 – Crear app
django-admin startapp person
Configurar app
tutofox\settings.py
... INSTALLED_APPS = [ ... 'rest_framework', 'person' ] ...
7 – Model
person\models.py
from django.db import models class PersonModel(models.Model): name = models.CharField(max_length=255) address = models.TextField() phone = models.BigIntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) class Meta: db_table = "person" ordering = ['-created_at']
8 – Serialize
person\serializers.py
from rest_framework.serializers import ModelSerializer from person.models import PersonModel class PersonSerializer(ModelSerializer): class Meta: model = PersonModel fields = ['id', 'name', 'address', 'phone'] #fields = '__all__'
9 – Views
person\views.py
from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from person.models import PersonModel from person.serializers import PersonSerializer class PersonApiView(APIView): def get(self, request): serializer = PersonSerializer(PersonModel.objects.all(), many=True) return Response(status=status.HTTP_200_OK, data=serializer.data) def post(self, request): #res = request.data.get('name') serializer = PersonSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(status=status.HTTP_200_OK, data=serializer.data) class PersonApiViewDetail(APIView): def get_object(self, pk): try: return PersonModel.objects.get(pk=pk) except PersonModel.DoesNotExist: return None def get(self, request, id): person = self.get_object(id) serializer = PersonSerializer(person) return Response(status=status.HTTP_200_OK, data=serializer.data) def put(self, request, id): person = self.get_object(id) if(person==None): return Response(status=status.HTTP_200_OK, data={ 'error': 'Not found data'}) serializer = PersonSerializer(person, data=request.data) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_200_OK, data=serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, id): person = self.get_object(id) person.delete() response = { 'deleted': True } return Response(status=status.HTTP_204_NO_CONTENT, data=response)
9 – Urls
person\urls.py
from django.urls import path from person.views import PersonApiView, PersonApiViewDetail urlpatterns_persons = [ path('v1/persons', PersonApiView.as_view()), path('v1/persons/<int:id>', PersonApiViewDetail.as_view()), ]
tutofox\urls.py
from django.contrib import admin from django.urls import path, include from person.urls import urlpatterns_persons urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(urlpatterns_persons)), ]
10 – Start API Server
python manage.py makemigrations python manage.py migrate python manage.py runserver
https://github.com/artyom-developer/api-rest-django-rest-framework-postgresql