How to Create a REST API in Django

There are multiple ways to write an API in Django, but I don’t want you confuse them. I will show you the two best ways to implement APIs, which will cover almost all the scenarios.

Both ways are similar to each other. They are:

  1. APIView
  2. ModelViewSet

APIView is more generic, while ModelViewSet is specific to a Model’s CRUD operations (i.e. ModelViewSet is used to perform List, Create, Read, Update, Delete (CRUD ) operations only.) Whereas with APIView, you can implement not only CRUD operations but also other Non-CRUD functionalities like login, logout, generate invoice, download invoice, change fields of multiple models, etc.

You must be thinking, “with APIView we can implement so much, why to learn ModelViewSet?” Well, you will figure out the reason very soon after implementing them both.

Let’s start with APIView first.

Prerequisite

Create a Django project and application using the following steps.

Shell

## Install django in your system from command prompt

pip install django

## Create Project

django-admin startproject DemoProject

## Create Application inside the Project

cd DemoProject

django-admin startapp DemoApplication

Add DemoApplication in settings.py > INSTALL_APPS list

INSTALLED_APPS = [

    'DemoApplication',

]


##### Install Django Rest Framework

Shell

Install django rest framework from command prompt

install djangorestframework

Add rest_framework application in settings.py > INSTALLED_APPS list

INSTALLED_APPS = [

    'rest_framework',

]


Now, we are ready with the Django Rest Framework setup. Let's create our first API using APIView.

### APIView

With APIView, we can implement Get, Post, Delete, Patch, Put methods. Let's create a Book data model and implement CRUD functionality on it.

<iframe class="ql-video" frameborder="0" allowfullscreen="true" src="https://www.youtube.com/embed/igXhsIgAU2g" height="315" width="560"></iframe>

Edit the file - **DemoProject > DemoApplication > models.py** and create a model. (Django will create a new SQL table in Database.)

Python

class Book(models.Model):

    id=models.IntegerField(primary_key=True)

title=models.CharField(max_length=200)

    author=models.CharField(max_length=200)
```

Edit the file - **DemoProject > DemoApplication > views.py**

Python

```
from rest_framework.views import APIView

from rest_framework.response import Response

from .models import *

from .serializers import *

from rest_framework import viewsets

Create your views here.

class BookApiView(APIView):

def get(self,request):

        allBooks=Book.objects.all().values()

return Response({“Message”:“List of Books”, “Book List”:allBooks})

    def post(self,request):

Book.objects.create(id=request.data[“id”],

                            title= request.data["title"],

author= request.data[“author”]

                            )

book=Book.objects.all().filter(id=request.data[“id”]).values()

        return Response({"Message":"New Book Added!", "Book":book})
```

Edit the file - **DemoProject > urls.py**

Python

```
from django.contrib import admin

from django.urls import path

from django.conf.urls import url

from ApiApplication import views

urlpatterns = [

path(‘admin/’, admin.site.urls),

    url("book/",views.BookApiView.as_view()), #new

]


Now, Migrate and run the project.

Shell

python manage.py makemigration

python manage.py migrate

python manage.py runserver


Open 127.0.0.1/book/ from your browser.

Voila! Your first API has created. 

Now Imagine, We have 10 data models (tables in database) and we have to create 10 such APIS and also implement CRUD functionality for the same. Isn't that a redundant task?

 To avoid repetitive code, Django has ModelViewSet where you can save 1000 of such lines.

#tutorial #python #api #django #crud #django development

What is GEEK

Buddha Community

How to Create a REST API in Django
Wilford  Pagac

Wilford Pagac

1594289280

What is REST API? An Overview | Liquid Web

What is REST?

The REST acronym is defined as a “REpresentational State Transfer” and is designed to take advantage of existing HTTP protocols when used for Web APIs. It is very flexible in that it is not tied to resources or methods and has the ability to handle different calls and data formats. Because REST API is not constrained to an XML format like SOAP, it can return multiple other formats depending on what is needed. If a service adheres to this style, it is considered a “RESTful” application. REST allows components to access and manage functions within another application.

REST was initially defined in a dissertation by Roy Fielding’s twenty years ago. He proposed these standards as an alternative to SOAP (The Simple Object Access Protocol is a simple standard for accessing objects and exchanging structured messages within a distributed computing environment). REST (or RESTful) defines the general rules used to regulate the interactions between web apps utilizing the HTTP protocol for CRUD (create, retrieve, update, delete) operations.

What is an API?

An API (or Application Programming Interface) provides a method of interaction between two systems.

What is a RESTful API?

A RESTful API (or application program interface) uses HTTP requests to GET, PUT, POST, and DELETE data following the REST standards. This allows two pieces of software to communicate with each other. In essence, REST API is a set of remote calls using standard methods to return data in a specific format.

The systems that interact in this manner can be very different. Each app may use a unique programming language, operating system, database, etc. So, how do we create a system that can easily communicate and understand other apps?? This is where the Rest API is used as an interaction system.

When using a RESTful API, we should determine in advance what resources we want to expose to the outside world. Typically, the RESTful API service is implemented, keeping the following ideas in mind:

  • Format: There should be no restrictions on the data exchange format
  • Implementation: REST is based entirely on HTTP
  • Service Definition: Because REST is very flexible, API can be modified to ensure the application understands the request/response format.
  • The RESTful API focuses on resources and how efficiently you perform operations with it using HTTP.

The features of the REST API design style state:

  • Each entity must have a unique identifier.
  • Standard methods should be used to read and modify data.
  • It should provide support for different types of resources.
  • The interactions should be stateless.

For REST to fit this model, we must adhere to the following rules:

  • Client-Server Architecture: The interface is separate from the server-side data repository. This affords flexibility and the development of components independently of each other.
  • Detachment: The client connections are not stored on the server between requests.
  • Cacheability: It must be explicitly stated whether the client can store responses.
  • Multi-level: The API should work whether it interacts directly with a server or through an additional layer, like a load balancer.

#tutorials #api #application #application programming interface #crud #http #json #programming #protocols #representational state transfer #rest #rest api #rest api graphql #rest api json #rest api xml #restful #soap #xml #yaml

An API-First Approach For Designing Restful APIs | Hacker Noon

I’ve been working with Restful APIs for some time now and one thing that I love to do is to talk about APIs.

So, today I will show you how to build an API using the API-First approach and Design First with OpenAPI Specification.

First thing first, if you don’t know what’s an API-First approach means, it would be nice you stop reading this and check the blog post that I wrote to the Farfetchs blog where I explain everything that you need to know to start an API using API-First.

Preparing the ground

Before you get your hands dirty, let’s prepare the ground and understand the use case that will be developed.

Tools

If you desire to reproduce the examples that will be shown here, you will need some of those items below.

  • NodeJS
  • OpenAPI Specification
  • Text Editor (I’ll use VSCode)
  • Command Line

Use Case

To keep easy to understand, let’s use the Todo List App, it is a very common concept beyond the software development community.

#api #rest-api #openai #api-first-development #api-design #apis #restful-apis #restful-api

Ahebwe  Oscar

Ahebwe Oscar

1620177818

Django admin full Customization step by step

Welcome to my blog , hey everyone in this article you learn how to customize the Django app and view in the article you will know how to register  and unregister  models from the admin view how to add filtering how to add a custom input field, and a button that triggers an action on all objects and even how to change the look of your app and page using the Django suit package let’s get started.

Database

Custom Titles of Django Admin

Exclude in Django Admin

Fields in Django Admin

#django #create super user django #customize django admin dashboard #django admin #django admin custom field display #django admin customization #django admin full customization #django admin interface #django admin register all models #django customization

Adonis  Kerluke

Adonis Kerluke

1596509565

RESTful API Design Driven Approach

In this tutorial I will show you the fundamentals of designing a RESTful API specification by applying REST principles and best practices, then you’ll be ready to try my online tutorial: How to design a REST API with API Designer?

If you already know what is meant by API in the context of RESTful web services, you can skip to the next section. If not, read on.

Level-Set on API

The abbreviation API stands for Application Programming Interface this in itself, does not help us understand what it is, however in the context of web services, it can refer to one of two things:

  1. The RESTful API specification is written using a modeling language such as Open API specification or RAML (RESTful API Modeling Language) that defines a contract for how software components can interact with a service.
  2. The implementation of a web service or microservice whose contract is designed by REST principles that describe how other services must interact with it.

In this post, I will use the first understanding of this term. Even though both are correct, the most technically relevant for this post is the first: an API is a contract for how software applications talk to each other.

Level-Set on REST

The acronym REST stands for REpresentational State Transfer. It is an architectural style used to represent the transmission of data from one application component to another. In the context of web services, we are talking about the representation of resources (i.e. data) transferred over HTTP by calling a URI that represents the data and via an HTTP method that represents the action to perform against the given data.

What Is RESTful API design?

RESTful API design is the activity of describing the behavior of a web service in terms of its data structures and the actions you allow other application components to perform on its data by the principles of REST. Those principles are covered later in this blog.

Why Design a RESTful API?

Imagine that you are an Architect (the kind the design building) and you set out to build an office block without a blueprint. You turn up on the first day with a truck full of bricks and some cement. What are the chances that you’ll be successful and build a structure that conforms to code and more importantly, doesn’t fall? It’s about zero. Without a blueprint the chance of failure is high.

The same approach applies to web service development. You need a blueprint, or more appropriately, an API specification. This is necessary to evaluate the API design and solicit feedback before even starting to build the implementation.

In addition to providing a specification for the web service’s development, an API contract serves to document its expected behavior, data types, and security requirements.

You should now be satisfied that API design is necessary for a RESTful web service, and should start to wonder how is the best approach to actually designing an API specification.

API Design Tooling

The tooling chosen by an API designer has substantial influence over the designer’s productivity. Highly productive tools such as the Anypoint API Designer from MuleSoft is perfect for designing APIs with OAS (swagger) or RAML.

#integration #api #rest #rest api #restful #api design #raml #rest api design