The Simplest Django REST Framework Example

Let’s Begin with our Data Model

Our Game Collection Data Model
# Django models for the Games app 
from django.db.models import CharField, IntegerField, Model, TextField
class Game(Model):
Game in our collection
name = CharField(max_length=500)
description = TextField()
notes = TextField()
rating = IntegerField()

Now the views — where the magic happens

# Django and DRF views for Game app

from rest_framework.serializers import ModelSerializer
from rest_framework.viewsets import ReadOnlyModelViewSet
from games.models import Game

class GameSerializer(ModelSerializer):
Class that converts models to JSON
class Meta:
model = Game
fields = '__all__'

class GameViewSet(ReadOnlyModelViewSet):
API for Games
queryset = Game.objects.all()
serializer_class = GameSerializer

The final step — configuring

# URLs for Games
from django.urls import include, path
from django.views.generic import RedirectView
from rest_framework import routers
from games.views import GameViewSet

games_api_router = routers.SimpleRouter()
games_api_router.register("", GameViewSet)

urlpatterns = [
path("", RedirectView.as_view(url="/games/api/")),
path("games/api/", include(games_api_router.urls)),
# Automatically Created API URLs from the Router:
# /games/api/ - list of all games (url name is 'game-list')
# /games/api/<pk> - detail of a single game based on its pk
# (url name is 'game-detail')

Accessing the API

DRF’s Auto-generated API Browser for Game List
http://localhost:8000/games/api/?format=json— Raw JSON output
Game Detail in the DRF API Browser




Technology-inspired creator.

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

Recommended from Medium

AMA : UniqueOneVN ➡️ Super Protocol

Kafka Streams : More Than Just a Dumb Storage


Back2Basics: The Story of Trait — Part 1


25 Tips I Wish I Knew Before I Started to Code

Introduction to GenericAPIView in Django Rest Framework

RESTful API — What You Need To Know

The Office — Data Analysis and Visualization with R

Beginner’s Guide to NativeScript (Part 3): Designing App Layouts for Android and iOS

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
Tim White

Tim White

Technology-inspired creator.

More from Medium

Django — Extended pagination

Handle MEDIA files in production — Django

floppy disks and Django media

A Django Blog In VS Code — Quick Start!

Build a REST API with Django REST Framework