RESTful APIs / RESTful APIs with Django and Django REST Framework

Getting Started with Django REST Framework

This tutorial will guide you through the process of setting up Django REST Framework. You'll learn how to install Django, start a new project, and install and configure Django RES…

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Covers building RESTful APIs using Django and Django REST Framework.

1. Introduction

In this tutorial, the goal is to set up Django REST Framework, a powerful and flexible toolkit for building Web APIs. You'll learn how to install Django, start a new project, and install and configure Django REST Framework.

What will you learn?

  • Installation of Django and Django REST Framework
  • Starting a new Django project
  • Setting up Django REST Framework

Prerequisites:

It's recommended to have a basic understanding of Python programming and some familiarity with web development concepts.

2. Step-by-Step Guide

Django and Django REST framework installation

First, we need to install Django and Django REST Framework. If you have Python installed, you can use pip (Python's package manager) to install these packages.

pip install django
pip install djangorestframework

Starting a new Django project

To start a new Django project, use the Django-admin command-line tool. Navigate to the directory where you want your project to live, then run the following command:

django-admin startproject myproject

Replace "myproject" with the name you want to give your project.

Setting up Django REST Framework

To use Django REST Framework, you'll need to add it to your installed apps in your settings.py file which is inside your Django project.

Open settings.py and locate the INSTALLED_APPS section and add 'rest_framework' to the list.

INSTALLED_APPS = [
    # ...
    'rest_framework',
]

3. Code Examples

Creating a simple API

Let's create a simple API. First, we'll need a Django app. You can create one using the following command:

python manage.py startapp api

In the models.py file of your new app, add the following code:

from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    profession = models.CharField(max_length=100)

This code creates a Person model with fields for name, age, and profession.

Next, we will create a serializer in serializers.py:

from rest_framework import serializers
from .models import Person

class PersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person
        fields = ['id', 'name', 'age', 'profession']

The serializer allows complex data such as querysets and model instances to be converted to Python native datatypes that can then be easily rendered into JSON.

Now, let's create a view in views.py:

from rest_framework import viewsets
from .models import Person
from .serializers import PersonSerializer

class PersonViewSet(viewsets.ModelViewSet):
    queryset = Person.objects.all()
    serializer_class = PersonSerializer

The ModelViewSet class is a type of ViewSet that provides default create(), retrieve(), update(), partial_update(), destroy() and list() actions.

Finally, we need to set up our URL routing in urls.py:

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import PersonViewSet

router = DefaultRouter()
router.register(r'persons', PersonViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

4. Summary

You've learned how to install Django and Django REST Framework and how to start a new Django project. You've also learned how to set up Django REST Framework and create a simple API.

Next steps include learning more about the Django REST Framework, such as how to work with serializers and viewsets in more detail, how to handle authentication and permissions, and how to test your APIs.

Some additional resources include the official Django REST Framework tutorial and the Django REST Framework documentation.

5. Practice Exercises

  1. Exercise: Create another model, serializer, and view for a new API endpoint. This model should have different fields than the Person model.

Solution: This will depend on the model you choose to create. For example, if you create a Job model, your model might look like this:

python class Job(models.Model): title = models.CharField(max_length=100) description = models.TextField()

Your serializer might look like this:

python class JobSerializer(serializers.ModelSerializer): class Meta: model = Job fields = ['id', 'title', 'description']

And your view might look like this:

python class JobViewSet(viewsets.ModelViewSet): queryset = Job.objects.all() serializer_class = JobSerializer

  1. Exercise: Modify the PersonViewSet to only allow listing and retrieving Persons, not creating, updating, or deleting.

Solution: You can do this by changing ModelViewSet to ReadOnlyModelViewSet:

python class PersonViewSet(viewsets.ReadOnlyModelViewSet): queryset = Person.objects.all() serializer_class = PersonSerializer

  1. Exercise: Add a search feature to the PersonViewSet that allows filtering Persons by name.

Solution: You can do this by adding a SearchFilter to the viewset:

```python
from rest_framework import filters

class PersonViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Person.objects.all()
serializer_class = PersonSerializer
filter_backends = [filters.SearchFilter]
search_fields = ['name']
```

For further practice, consider building a more complex API with multiple related models and endpoints, or exploring more advanced features of the Django REST Framework, such as pagination and throttling.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

Random Password Generator

Create secure, complex passwords with custom length and character options.

Use tool

Color Palette Generator

Generate color palettes from images.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help