Modern Django — Part 2: REST APIs, Apps, and Django REST Framework

Dylan Stein Blocked Unblock Follow Following May 29, 2017

Introduction

The previous technical portions of the guide can be found here:

After completing those sections, we now have a solid base waiting for additions! This portion begins with a crash course in HTTP. Following that, a clarification on the concept of “applications” in Django. Finally the great wall of text will end with a brief introduction to Django REST Framework.

After the concepts are explained, we will meet some of Django REST Framework’s key functions. They will be used to build an API application to perform functions on the built-in User model. Along the way, we will learn how to interact with REST APIs in the terminal.

Technology

The technology used in this section will include those associated to Django applications, basic HTTP and REST standards, Django REST Framework, and programs useful for working with APIs in the terminal.

Django Applications: “The term application describes a Python package that provides some set of features. Applications may be reused in various projects” (source). A Django project consists of a number of Applications that can be reused in other projects. More on Django Applications below.

describes a Python package that provides some set of features. Applications may be reused in various projects” (source). A Django project consists of a number of Applications that can be reused in other projects. More on Django Applications below. HTTP: Stands for Hypertext Transfer Protocol. “HTTP functions as a request–response protocol in the client–server computing model” (source).

HTTP methods/verbs: Methods defined by HTTP standards that “indicate the desired action to be performed on the identified resource” (source). The basic methods are GET and POST. A number of others exists such as DELETE, PUT, PATCH, etc. A specific URL can have multiple functions based on the method passed to it in the HTTP request.

RESTful: Stands for Representational State Transfer. “REST-compliant Web services allow requesting systems to access and manipulate textual representations of Web resources using a uniform and predefined set of stateless operations” (source). What this means is that REST applications have a standard set/structure of HTTP resources that provide data to the clients from the server based on the HTTP method used.

Django REST Framework: “Django REST framework is a powerful and flexible toolkit for building Web APIs” (source). We will use the Django REST Framework application to easily integrate a REST API into existing Django functionality!

Walkthrough

1. Crash Course in HTTP and REST

Without delving into a complete understanding of networking, I will explain HTTP (Hypertext Transfer Protocol).

1-A. How the Internet Works in Layers

There are 4 large layers in the Internet Protocol Suite. They include:

Application Layer Transport Layer Internet Layer Link Layer

HTTP (Hypertext Transfer Protocol) is the structure for holding “data.” It is at the top most layer, the Application Layer. It is moved around the internet via the Transport Layer. Common Transport Layer technologies include TCP and UDP. TCP/UDP packets wrap HTTP and are moved along via the Internet and Link Layers. A broader understanding of how networking and the Internet works can be found by reviewing the 7 Layer OSI Model.

1-B. URLS and Resources

HTTP is typically accessed and used through the form of an HTTP URI. A URI is a Uniform Resource Identifier. A URL (Uniform Resource Locator) is a specific type of URI used to identify a web address. So, when we talk about a link such as https://www.instagram.com we are talking about an HTTP resource. That is, an HTTP URI, taking the form of an HTTP URL.

We use URLs to define HTTP resources that are available to us. They should be self-explanatory! Such as https://www.instagram.com/accounts/login/ describing a resource of logging in a user.

1-C. HTTP Requests and Responses

HTTP resources are provided via requests and responses. An HTTP request says “give me this” or “do something” to a server. The server will do a number of processes based on the data from the request, determining which functions should be called and what data should be returned. Once those processes are completed, the server sends back an HTTP response. That response says “I did this” or “take this <resource>” with success/error messaging.

1.4 HTTP Methods

When an HTTP request is made, it is given a specific method that defines the action it will take on a resource. A particular resource available by a URL can take HTTP requests with different types of methods, and may perform different functions based on the method specified.

The most important HTTP methods to know are GET and POST .

GET : used to retrieve data! Get a homepage, get images on Instagram

: used to retrieve data! Get a homepage, get images on Instagram POST : send data to the server! Such as login, post a picture on Instagram

All other HTTP methods are pretty self explanatory. You can read more here.

To show how an HTTP resource can take different types of HTTP request + method combinations, we will use an example URL from Instagram:

https://www.instagram.com/media/<media-id>/likes

Documentation for this API can be found here.

This URL allows us to perform operations upon a user’s photo or video likes. By making different HTTP requests to this URL different operations can be done:

Requesting with GET : will return a list of all the likes on the media

: will return a list of all the likes on the media Requesting with POST : will have the current user like the media

1.5 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:

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

When using the manage.py runserver command you will see requests, methods, responses, and status codes being show in the terminal! Two GET request/responses are shown below. One has an internal server error denoted by the 500 error and one returned 200 OK for the root URL.

Example of two GET request/responses!

1.6 RESTful API

The HTTP resource from Instagram used earlier, is part of their RESTful API!

https://www.instagram.com/media/<media-id>/likes

As described above, REST stands for Representational State Transfer. RESTful APIs are a structured set of HTTP resources. Those resources describe functions/database models and perform manipulation upon those structures via a set of standard HTTP requests.

These standards specify how URLs should be structured and what functions should happen based on a given HTTP methods. RESTful APIs should be structured such that all resources represent a data model. Methods supplied to the resource should be self explanatory. GET ing a resource should return all of values of that model, such as users/ returning all users in the database. If say a Primary Key value (association in the database) is supplied, it should return only that user’s data users/1/ . Again, using the same resource with POST would require the necessary data to create a new user. POST on users/1/ would represent the ability to update the data for user 1.** There are a number of other specifics that we will go over when writing the API!

We should structure all of our URLs to map to our database models to make it as RESTful as possible! We should NOT create resources that provide random arbitrary functions by requesting them.

** In a standard workflow we would use PUT or PATCH for these types of function. However we are talking in basic examples here.

1.7 Summary

For the time being, the above should hold you over as we create a base API. However in the future, mastering HTTP concepts will be essential for writing custom APIs and custom response handlers on the front end.