What are REST and APIs
If you hang around developers long enough you will start hearing the word REST very often and so we begin our adventure by giving a simple definition of the term. The REST acronym stands for Representational State Transfer, which is an architectural design. So it follows that when developers use the words RESTful, what is being referred to is an application that implements the REST architectural design.
Next on our list of definitions would be the term API. This simply stands for Application Programming Interface. It is a software intermediary that allows two applications to talk to each other. Each time you use an app like Facebook, send an instant message or check the weather on your phone, you’re using an API. In other words, we interact with it at a lower level at the source code, writing functions and routines.
If broken down into simplified speech, we can take RESTful API as web services or Web APIs which are usually how your applications are linked to third-party services such as external applications or websites. This is usually because only a small portion of your site is exposed and you get to customize the exact information being transmitted. This communication can be data-oriented, in a sense that the RESTful API simply makes available the information you store in your databases using a format such as XML or JSON. One of the key advantages here is being able to access data without having to be directly connected to the database. Hence the type of database doesn't matter, the database itself remains secured plus it's an easy way to change and update information as required.
There are two sides to the RESTful API equation. One is the provider and the other being the consumer. For now, we are taking a look at the consumer side of things. The best way to start off is by writing codes that access public APIs. The techniques learned here can be adapted to other RESTful APIs with minor mods, plus once you learn the steps you can apply to many problems.
What you need to know before building your REST API
Most APIs are slow
Without caching, the API response/request cycle could be really slow since they are an extra step that the server-side has to run through. This usually leads to a considerable increase in the overall time it takes to perform each task. A workaround to this is to have a cache setup.
You have no control
Third-party APIs are just that, third-party. You do not own then and can only connect to them. This means that they are subject to change on the whelm of the developer. So from time to time, you might have to readjust your coding or might be left with a broken app.
There is a limit to the number of requests you can make
When integrating an API, it would be wise to note the number of requests you can perform each hour This is usually done as a security measure to prevent an overload of requests. Caching usually is the solution for the rate limits.
Keep things secured
It’s a must to keep all sensitive data out of public repositories. While some APIs will require authentication to access, it’s still best to approach this into things from a security-conscious perspective.
APIs only tell a part of the story and without proper documentation, it becomes hard to figure out what does what and at what point. Unless the API server is open source, but then searching for specific coding directly in the source code can be very hard and time-consuming. Always wiser to make sure that reliable documentation is available or being implemented before starting out.
Some Best Practices to Take Note Of
Before we commence there are simple rules that one should adhere to when building or coding REST APIs. However, this does not claim in any way to be the de facto best practices for REST API creation. Just what we consider to be the minimum standard to maintain.
Having said that, RESTfull API design is a craft in and of itself. It's an ever-evolving process and we all learn new tips and tricks each day.
So here are our recommendations for creating clean functional REST APIs:
The first on the list is to have a good grasp of the HTTP protocol as it related to REST. This will help you make better design decisions down the road. Understanding HTTP verbs such as GET, POST, PUT, PATCH and DELETE are the most common to start with.
As much as it might be tempting, you shouldn't return plain text. While this isn't forced by the REST architectural style, most REST APIs use JSON as a data format. Nonetheless, it is not enough to return a body comprising a JSON-formatted string. It is best to specify the Content-Type header also. This should be set to the value application/JSON.
The reason why this is so important is due to programmatic clients that rely on this header to correctly decode the response. Take for example a service interacting with your API via the requests library in Python
A quick rundown on other best practices include
Avoid using verbs and use plural resource nouns.
You should always return error details in the response body
Pay attention to status codes that are generated
It’s never a good idea to nest resources
Handle trailing slashes gracefully
Make use of the query string for filtering and pagination
There is a difference between 401 Unauthorized and 403 Forbidden
202 Accepted is your friend and should be fully utilized
You should use a web framework specialized in REST APIs whenever you can
Why you should build a REST API using Django REST Framework?
The one reason developers give for using Django REST Framework is that it makes serialization simple and easy.
When using Django you would just have to define your models for your database using Python. Django ORM handles all the database migrations and queries.
Think of the Django ORM like a curator, pulling the data you need when you need it without having to do so yourself.
As a developer, this frees you up to worry about the business logic of your application and forget about the low-level implementation details. Django ORM handles all that for you.
The Django REST Framework, then, plays nicely with the Django ORM that’s already doing all the heavy lifting of querying the database. Just a few lines of code using Django REST Framework, and you can serialize your database models to REST-ful formats.
Django Rest Framework (DRF) Quick Start
We will be making use of Python 3.6, Django 1.11 and Django Rest Framework 3.6 to construct spells contained here. Plus we will also assume that every command is run inside a virtualenv. If you’re not familiar with it, no problem, just use sudo pip instead of pip. If you don’t have Python 3.6 yet, you shall port (or remove) str methods as they use newly formatted string literals.
$ pip install django djangorestframework
To create a Django project for this demo you just have to use the following command:
$ django-admin startproject demo && cd demo
DRF’s Serializers convert model instances to Python dictionaries, which can then be rendered in various API appropriate formats - like JSON or XML. Similar to the Django ModelForm class, DRF comes with a concise format for its Serializers, the ModelSerializer class.
To begin our API development process we must first create some serializers to handle our data interchange (DRF uses JSON by default but you can change that to XML or YAML). Some developers are of the opinion that this could be made automatically on the ViewSet level. They are unaware that making an API is much like creating a more complex Form-View combo which is no easy feat on its own.
Viewsets and routing
Our next step is to write the basic viewsets. A quick note: Usually when writing an API-only backend, it’s easier to use views.py for API views. If there is a need to separate API views from other web views, then you can put this code into e.g. api.py but you should remember to update imports in other files accordingly.
# project/views.py from rest_framework.viewsets import ModelViewSet from .serializers import AuthorSerializer, BookSerializer from .models import Author, Book class AuthorViewSet(ModelViewSet): serializer_class = AuthorSerializer queryset = Author.objects.all() class BookViewSet(ModelViewSet): serializer_class = BookSerializer queryset = Book.objects.all()
The final step is to create a basic routing for the API and connect the ViewSets:
# demo/api.py from rest_framework.routers import DefaultRouter from project.views import AuthorViewSet, BookViewSet router = DefaultRouter() router.register('authors', AuthorViewSet) router.register('books', BookViewSet) # project/urls.py from django.conf.urls import url, include from django.contrib import admin from .api import router urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include(router.urls)) ]
It should be noted that the Django REST Framework will not filter the query sets for a built-in API browser. This means it will allow you e.g. to select any author even if you are on a specific author’s book list. With this, we can say you should be able to build a REST API using the Django REST Framework.