Let us first talk about what is a database. A database is a central area for storing data in a organized fashion. Everytime you go on an app and see your friend's latest instagram post this is made possible because that data is stored in a database. A database is made up of what we call tables. A table is simply a representation of an entity in a database. An entity generally consits of a set of attributes and this entity can have relationship with other entities.
A database management system is the software responsible for managing and organizing the database. Examples of DBMS systems include
- MySQL
- PostgreSQL
Everytime you use your web browser to login to facebook or use google maps on your phone to find the closest coffee shop is made possible because the app on your phone or the browser on your computer is making use of an API. API stands for Application Programming Interface and basically acts as the middle man between your app or web browser which we call clients and the database stored on a server.
The API recieves a request from a client. The API proceeds to service that request by querying the databse for the data that the client needs and the returns the data in a suitable format such as JSON.
There several different api request types depending on the function that you are trying to perform. The function that you perform usually falls within the CRUD family. Each crud function has a corresponding request type shown in parentheses.
- CREATE (POST)
- READ (GET)
- UPDATE (PUT)
- DELETE (DELETE)
JSON is a data format that is human readable and easier to parse. It resembles a dictionary where keys could represent attributes and values represent the actual values for those attributes.
Let us now look at an example. Imagine you are the owner of a bookstore. In a bookstore you have several entities that you may want to represent such as Customers, Books etc. Each of these entities can be represented as a table in our database. For this example we are going represent the Book table. Let us look at how this Book table might look in our database.
A book has several attributes
- title
- author
- price
Here is an example of how that table might look.
id | title | author | price |
---|---|---|---|
1 | Moby Dick | Herman Melville | 25.30 |
2 | 48 Laws of Power | Robert Greene | 30.0 |
3 | Pride and Prejudice | Jane Austen | 21.50 |
For the rest of this tutorial we are going to use the django framework to create an endpoint for our book table. An endpoint allows some manipulation of data to the database by accepting a request from a client. Our endpoint will accept a GET request from a client and return a JSON response with all the books in the database. This assumes you have already set up django and the database.
The first thing we need to do is to create our Book model. Open your models.py file and add the following code
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=255)
author = models.CharField(max_length=255)
price = models.FloatField(max_length=255)
def __str__(self):
return self.title
The first thing you will notice is we extended the models.Model class to allow the creation of database models. For each property we also defined
the data type. So for the fields that are strings we use the models.CharField()
and for the price that is a float we use models.FloatField()
.
Also notice we did not have to specify an id field, that is because the id field is automatically generated by django. Read more about the different types of
fields here.
Run the following commands in the folder that has your manage.py file. This allows your database to be updated with the new model that you created. A table will be created with the same name.
python manage.py makemigrations
python manage.py migrate
We need to register the model so we can see it in the admin console. To do this edit the admin.py file and add the following code.
from django.contrib import admin
from core.models import Book
admin.site.register(Book)
Next we are going to create a serializer. A serializer allows our model to be easily converted to json format. Open serializers.py and add the following code.
from rest_framework import serializers
from core.models import Book
class BookSerializer(serializers.ModelSerializer):
model = Book
fields = ('id', 'title', 'author', 'price')
Now it is time to create the view. The view contains the endpoint for our request. We are going to use a class based view. We extend APIView from the rest_framework library. This allows us to override methods such as get, post, put which corresponds to possible request types. In this example we are going to override the get method since this is a GET request.
from rest_framework.views import APIView
from rest_framework.response import Response
from core.models import Book
from core.serializers import BookSerializer
class BookView(APIView):
def get(self, request, format=None):
books = Book.objects.all()
serializer = BookSerializer(books, many=True)
return Response(serializer.data)
What we did here is to create a view by extending the APIView class. Django will determine what function to run depending on what type of request comes in.
If a GET request comes in then it will call the get method and if a POST request comes in then it will call the post method. Inside the get method we first
retrieve all the books from the database which is returned as a queryset. We next use the serializer to convert it to JSON format.
We specify many=True
because there could be multiple books present. Lastly we return a response with the json data from the serializer.
Now we need to define the url we are going to use to link our endpoint. Edit the urls.py and add the following code.
from django.urls import path
from core.views import BookView
urlpatterns = [
.....
path('books/', BookView.as_view())
]
Essenetially what is happening here is whenever a request is sent to the <domain_address>/books/ url, the BookView will handle that request.
Now it is time to test. First run the server python manage.py runserver
.Go to the admin console at http://127.0.0.1:8000/admin and sign in with your superuser username and password. You should
see the Books model in the admin console, simply click on it and add a few books. After which either using postman or a browser send a GET request to
http://127.0.0.1:8000/books/ and you should see somthing similar to below.
[
{
"id" : 1,
"title" : "Moby Dick",
"author": "Herman Melville",
"price": 25.30
},
{
"id": 2,
"title": "48 Laws of Power",
"author": "Robert Greene",
"price": 30.0
},
{
"id": 3,
"title": "Pride and Prejudice",
"author": "Jane Austen",
"price": 21.50
}
]