How to create an REST API using Django rest framework, with example

Jan. 5, 2023


0
4 min read
462

In this article we will see how to create an API.

what is rest API?

REST (Representational State Transfer) API is a software architectural style that defines a set of constraints to be used for creating Web APIs. It is based on the following principles:

  1. Client-server architecture: The client and server are separated, allowing them to evolve independently.

  2. Statelessness: The server does not store any state about the client sessions in the form of cookies, sessions, or similar mechanisms.

  3. Cacheability: The server indicates to the client whether a response can be cached or not, allowing the client to use a cached copy of the response if available.

  4. Layered system: The server can be composed of multiple layers (e.g., load balancers, caches, application servers) without the client being aware of it.

  5. Code on demand (optional): The server can include executable code in its responses, which the client can execute.

REST APIs are typically built using HTTP, and support the following HTTP methods:

  • GET: Used to retrieve a resource.
  • POST: Used to create a new resource.
  • PUT: Used to update an existing resource.
  • DELETE: Used to delete a resource.

REST APIs are used in modern web and mobile applications to communicate with servers, retrieve data, and perform various operations. They are a convenient and flexible way to expose the functionality of a backend system to the client, and are typically implemented using a framework such as Django Rest Framework (DRF) or Flask-RESTful.

How you can create an API using Django Rest Framework (DRF):

  1. Install Django and DRF:
    $ pip install django
    $ pip install djangorestframework
  2. Create a new Django project
    $ django-admin startproject myproject
    
  3. Create a new Django app:
    $ python manage.py startapp myapp
    
  4. Add 'rest_framework' to INSTALLED_APPS in your project's settings.py file:
    INSTALLED_APPS = [
        ...
        'rest_framework',
    ]
    
  5. Define your model in models.py. For example:
    from django.db import models
    
    class Person(models.Model):
        name = models.CharField(max_length=128)
        email = models.EmailField()
        phone = models.CharField(max_length=16)
    
  6. Run the following command to create the database tables for your models:
    $ python manage.py makemigrations
    $ python manage.py migrate
    
  7. Create a serializer class in serializers.py to convert your model instances into JSON format:
    from rest_framework import serializers
    from .models import Person
    
    class PersonSerializer(serializers.ModelSerializer):
        class Meta:
            model = Person
            fields = ['id', 'name', 'email', 'phone']
    
  8. Create a view in views.py to handle HTTP requests:
    from django.shortcuts import render
    from rest_framework import viewsets
    from .models import Person
    from .serializers import PersonSerializer
    
    class PersonViewSet(viewsets.ModelViewSet):
        queryset = Person.objects.all()
        serializer_class = PersonSerializer
    
  9. Define the URL patterns in urls.py:
    from django.urls import include, path
    from rest_framework import routers
    from . import views
    
    router = routers.DefaultRouter()
    router.register(r'persons', views.PersonViewSet)
    
    urlpatterns = [
        path('', include(router.urls)),
    ]
    
  10. Start the development server:
    $ python manage.py runserver
    

Now you can use HTTP requests to interact with your API at http://127.0.0.1:8000/persons/.

For example, you can use the following command to send a GET request to retrieve a list of all persons:

$ curl -X GET http://127.0.0.1:8000/persons/

You can also use the following command to send a POST request to create a new person:

$ curl -X POST -H "Content-Type: application/json" -d '{"name": "John Smith", "email": "john@example.com", "phone": "555-555-5555"}' http://127.0.0.1:8000/persons/

You can use postman for testing this API

You can check this course also Building APIs with Django and Dajngo rest framework

I hope this helps! If you have any problems you can comments

django API django-rest-framework Appreciate you stopping by my post! 😊

Add a comment


Note: If you use these tags, write your text inside the HTML tag.
Login Required
Author's profile
Profile Image

Zehra Ahmad

Dian Alphabet