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:
-
Client-server architecture: The client and server are separated, allowing them to evolve independently.
-
Statelessness: The server does not store any state about the client sessions in the form of cookies, sessions, or similar mechanisms.
-
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.
-
Layered system: The server can be composed of multiple layers (e.g., load balancers, caches, application servers) without the client being aware of it.
-
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):
- Install Django and DRF:
$ pip install django $ pip install djangorestframework
- Create a new Django project
$ django-admin startproject myproject
- Create a new Django app:
$ python manage.py startapp myapp
- Add 'rest_framework' to INSTALLED_APPS in your project's settings.py file:
INSTALLED_APPS = [ ... 'rest_framework', ]
- 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)
- Run the following command to create the database tables for your models:
$ python manage.py makemigrations $ python manage.py migrate
- 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']
- 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
- 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)), ]
- 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