RESTful API

Sarthak Kumar
9 min readFeb 11, 2019

--

Before talking about REST APIs lets first talk about what an API is in general

What is an API?

An API stands for Application Program Interface, there are all kinds of APIs but we are specifically talking about Web APIs here. There are APIs in our computers,smartphones and even some refrigerators etc. Some of the key points of the APIs are :~

  • Application Program Interface
  • APIs are everywhere
  • It is basically a contract provided by one piece of software to another piece of software
  • It usually consists of a structured request and a structured response

Some of the best analogies of APIs are:~

  • Think of yourself sitting at a table at a restaurant(here you are one piece of software such as a web application on the client side) and the kitchen is the server or the service that processes a certain request while the waiter is an API, he’s formatted to take a certain order in a specific way and then to bring back a certain order i.e. the data object response that you requested and the API is basically a messenger or waiter between running software
  • Another good analogy could be a toy box which can only insert certain shapes, so if we were to think that box as an API then it is formatted to take certain shapes so the client has to format the request as a circle,square,triangle etc. anything else wont be accepted you will get some kind error message or response, this is similar to how an API works and you can think of these shapes as the API standards such as JSON or SOAP etc. To make this toy box operate even more like an API we could have some kind of output once the formatted shape request go in and that would be your response

What is REST?

  • REST stands for Representational State Transfer.(State — the state of the application (web site) on a client’s computer changes as the client clicks from one link to the next. Ask the client clicks on the link, they request additional resources, and the application “state” changes.The state in rest is best explained here https://restfulapi.net/statelessness/)
  • It’s an architecture style for designing network applications.
  • It works by relying on a stateless,client-server protocol, almost always HTTP(you can use other protocols with REST too but HTTP is by far the most used because in order to use real world REST we need the delivery methods that HTTP offers).
  • Treats server objects as resources that can be created,updated,deleted etc(example of server side object could be blog post etc.).
  • Can be used by virtually any programming language.

Constraints

Since it is not a formally defined protocol there are many opinions on the details of implementing REST APIs. However, the following five constraints must be present for any application to be considered RESTful:

  • Client-server: A client-server architecture allows a clear separation of concerns. The client is responsible for requesting and displaying the data while the server is taking care of data storage and application logic. One advantage is that both sides can be developed separately as long as the agreed-upon request format is followed.
  • Statelessness: Communication between client and server is stateless. This means that every client request contains all the information necessary for the server to process the request. This further reduces server complexity since no global state (other than a possibly shared database) is necessary and improves scalability since any request can be processed by any server.
  • Caching: Stateless client-server communication can increase server load since some information may have to be transferred several times so requests that only retrieve data should be cache-able.
  • Layered system: A key feature of most networked systems. In the context of REST, this means that a client can not necessarily tell if it is directly communicating with the server or an intermediate (proxy).
  • Uniform interface: REST defines a set of well defined operations that can be executed on a resource

HTTP Methods

  • GET : Retrieve data from a specified resource.
  • POST : Submit data to be a processed to a specified resource (more secure than GET).
  • PUT : Update a specified resource (used to update a specified resource so usually we would have to send some kind of id so server knows which object to update and you cant make a PUT request from a form we have to use AJAX for it or for some frameworks like Angular we have modules like HTTP module which can be used for it).
  • DELETE : Delete a specified resource (we need to send some kind of id in it also).
  • HEAD : Same as GET but does not return a body.
  • OPTIONS : Returns the supported HTTP methods.
  • PATCH : Update partial resources.

Status Codes

After a request has been processed, the server will attempt to send an HTTP response back to the client. The beginning of the response will contain a status code for the outcome of the request.

Wikipedia states that status codes are broken up into five different major groups (source). These groups and a common example are below:

  1. Informational 1XX: Probably won’t encounter 1XX’s often
  2. Successful 2XX: 200 OK (getting a page)
  3. Redirection 3XX: 304 Not Modified (cached CSS has not changed)
  4. Client Error 4XX: 404 Not Found (page does not exist)
  5. Server Error 5XX: 500 Internal Server Error (generic error)

When using the manage.py runserver command in Django you will see requests, methods, responses, and status codes being show in the terminal!

Endpoints

The URI/URL where API/service can be accessed by a client application.

Notice that in the above example of endpoints the GET and POST method have the same endpoints or urls but since they are different methods/requests that’s okay.

Authentication

Public or open APIs dont require any kind of authentication but some APIs require authentication to use their service. This could be free or paid. Authentication could mean just registering your app with the providers API and even sometimes we will have to pay for it or purchase that data access.

There are a couple of ways that authentication is implemented such as HTTP Basic Authentication, API Keys, OAUTH etc. To know more about them click on the link below :~

Usually you will use OAUTH as authentication which involves getting some kind of access token and sending that along with your request so if you tend to make a request without that you will get some kind of unautherized error.

One example of one such API is GithubAPI which is a really nice API for beginners and is easy to use and how it works is that you can use it without any kind of authentication but only upto a certain number of requests per hour and if you go over that you wont be able to make requests unless you authenticate.

Why Django REST Framework?

Django REST Framework (REST Framework) provides a number of powerful features out-of-the-box that go well with idiomatic Django, including:~

  1. Browsable API: Documents your API with a human-friendly HTML output, providing a beautiful form-like interface for submitting data to resources and fetching from them using the standard HTTP methods.
  2. Auth Support: REST Framework has rich support for various authentication protocols along with permissions and throttling policies which can be configured on a per-view basis.
  3. Serializers: Serializers are an elegant way of validating model querysets/instances and converting them to native Python datatypes that can be easily rendered into JSON and XML.
  4. Throttling: Throttling is way to determine whether a request is authorized or not and can be integrated with different permissions. It is generally used for rate limiting API requests from a single user.

Plus, the documentation is easy to read and full of examples. If you’re building a RESTful API where you have a one-to-one relationship between your API endpoints and your models, then REST Framework is the way to go.

Types of Views in Django Rest Framework and when to use them in your API

Django Rest Framework offers two helper classes we can use to create the endpoints of our API i.e APIView and Viewset. Both ways are slightly different and offer their own benefits.

APIViews

APIView is the most basic type of view we can use to build our API,It enables us to describe the logic which makes our API endpoint.

So what is the API view? An API view allows us to define functions that match the standard HTTP methods.

  • HTTP GET: to get one or more items
  • HTTP POST: to create an item
  • HTTP PUT: to update an item
  • HTTP PATCH: to partially update an item
  • HTTP DELETE: to delete an item.

By allowing us to customize the function for each HTTP method on our API URL, API views give us the most control over our application logic.
application logic. This is perfect in cases where you need to do something a little bit different from simply updating objects in the database, such as calling other apis or working with local files. So when should you use API views? A lot of the time it will depend on personal preference as you learn more about the Django rest framework. Here are some examples for when it might be better to use API views :~

  • Whenever you need full control over your application logic, such as when you’re running a very complicated algorithm or updating multiple data sources in one API call.
  • Or when you’re processing files and rendering asynchronous response(Maybe you’re validating a file and returning the result in the same call.)
  • Another time you would use it is when you are calling other external APIs or services in the same request.
  • And finally,you might want to use API views when you need to access local files or data.

Viewsets

So what are viewsets? Just like API views, viewsets allow us to write the logic for our endpoints. However instead of defining functions which map to HTTP methods, viewsets accept functions that map to common API object actions, like:~

  • LIST: for getting a list of objects.
  • CREATE: for creating new objects.
  • RETRIEVE: for getting a specific object.
  • UPDATE: for updating an object.
  • PARTIAL UPDATE: for updating part of an object and
  • DESTROY for deleting an object.

Additionally viewsets take care of a lot of the common logic for us, they are perfect for writing APIs that performs standard database operations and they are the fastest way to make an API which interfaces with a database back-end. So when should you use viewsets? Well, a lot of the time this will come down to personal preference. However here are some examples of cases when you might want to choose a viewset over an API view:~

  • When you need a simple CRUD(Create,Read,Update and Delete) interface to your database model.
  • You need a quick and simple API to manage predefined objects.
  • Or maybe you need very little custom logic additional to the viewsets features already provided by the Django rest framework
  • You are working with standard data structure.

Serializers

We must first create some serializers. Serializers are defined by DRF as:

Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

The serializers in REST framework work very similarly to Django’s Form and ModelForm classes. We provide a Serializer class which gives you a powerful, generic way to control the output of your responses, as well as a ModelSerializer class which provides a useful shortcut for creating serializers that deal with model instances and querysets.

With that we can break serializers down to two main uses:

  1. Get model data from the database in JSON
  2. Use them like forms to validate data and create instances of a model

There are different types of serializers, but we will focus our efforts today on HyperlinkedModelSerializers. To understand them, we must first look at ModelSerializers:

The ModelSerializer class is the same as a regular Serializer class, except that:

It will automatically generate a set of fields for you, based on the model.

It will automatically generate validators for the serializer, such as unique_together validators.

It includes simple default implementations of .create() and .update().

HyperlinkedModelSerializers build on top of ModelSerializers by using a URL instead of primary key values to define relations. Thus when getting data back from a serializer, you will get a field url instead of pk.

All of those things can manually be done, however we should opt to use HyperlinkedModelSerializer 9 times out of 10 when dealing with Model manipulation. In more advanced cases, we may need to write an entire Serializer by hand.

Full documentation on DRF Serializers can be found here.

--

--

Sarthak Kumar

I’m a Software Engineer(Backend) who blogs sometimes and loves to learn and try new tools & technologies. My corner of the internet : https://sarthakkumar.xyz