API — REST en 5 minutos con Django REST Framework

$>python manage.py startapp phrases
from django.db import modelsclass Author(models.Model):
slug = models.SlugField(primary_key=True)
name = models.CharField(max_length=200)
description = models.TextField()
class Meta:
db_table = 'authors'
class Phrase(models.Model):
author_slug = models.ForeignKey(Author, db_column='author_slug', on_delete=models.DO_NOTHING)
text = models.TextField()
class Meta:
db_table = 'phrases'
$>python manage.py makemigrations phrases
$>python manage.py migrate phrases
# Django Rest Framework
from rest_framework import serializers
# Models
from .models import Author, Phrase
class AuthorSerializer(serializers.ModelSerializer):
class Meta:
model = Author
fields = ('slug', 'name', 'description')
class PhraseSerializer(serializers.ModelSerializer):
author = AuthorSerializer(source='author_slug', read_only=True,)
class Meta:
model = Phrase
fields = ('id', 'text', 'author_slug', 'author')
# Django Rest Framework
from rest_framework import viewsets
# Models
from .models import Author, Phrase
# Serializers
from .serializers import AuthorSerializer, PhraseSerializer
class AuthorViewSet(viewsets.ModelViewSet):
serializer_class = AuthorSerializer
queryset = Author.objects.all()
class PhraseViewSet(viewsets.ModelViewSet):
serializer_class = PhraseSerializer
queryset = Phrase.objects.all()
# Django
from django.urls import include, path
# Django Rest Framework
from rest_framework import routers
# Views
from . import views
router = routers.DefaultRouter()router.register(r'authors', views.AuthorViewSet, basename='authors')
router.register(r'phrases', views.PhraseViewSet, basename='phrases')
urlpatterns = [
path('', include(router.urls)),
]
GET /authors/ # List
GET /authors/{id}/ # Show
POST /authors/ # Create
PUT /authors/{id}/ # Update
PATCH /authors/{id} # Partial Update
DELETE /authors/{id} # Delete
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('phrases.urls')), #Our app
]

--

--

Innovador por naturaleza, desarrollador de software de profesión y futbolista de corazón.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pedro Caicedo

Pedro Caicedo

8 Followers

Innovador por naturaleza, desarrollador de software de profesión y futbolista de corazón.