Creating an API for Your Android App
Part 1: Creating the API
This past year, I’ve been working on setting up a small app for local farmers that would help buyers know what products farmers have available and what’s in stock at the moment. The concept was simple: the farmer information would be contained in a RESTful API, and the app would communicate with the API to make this information available to users.
As I began to research this process, I found that the documentation for many steps of this process was often confusing, sparse and hard to get started with, especially if you’re using Windows (which many beginners do). In this tutorial, I’ll go through all of the steps of creating the backend of such an app.
Requirements
In this tutorial, I’ll only be writing the back-end for a Kotlin app in Android Studio. I’ll be using:
Setting up the environment
First, create a directory for your project and enter into it. I use Git Bash as my terminal of choice, because it allows me to use some Linux-based tutorials and templates without finding the Windows-specific terminology and commands.
(Note that Django only allows letters, numbers and underscores for project names.)
$ mkdir farmer_database_app
$ cd farmer_database_app
In Python, you’ll want to have a virtual environment for each project to keep track of the packages you’re using and what you have installed. You can do this with the command:
$ python -m venv env
Then, activate it with the activate file. Look for the activate.bat
file to find which directory this is in. On Windows, your path will likely be env/Scripts/activate
. Run:
$ source env/Scripts/activate
Setting up the database
First, install Django with
$ pip install django
You can then start the Django app with the django-admin commands startproject
and startapp
:
$ django-admin startproject farmer_database_app .
$ django-admin startapp farmer_database
This creates two directories: farmer_database_app
and farmer_database
respectively.
- The
startproject
command creates a package directory and amanage.py
file. The“.”
command creates these in the working directory. - The
startapp
command creates an app directory structure. This contains the models and templates for your app.
Add the app to the INSTALLED_APPS portion of the settings.py
file inside the package directory (farmer_database_app
):
INSTALLED_APPS = [
...,
'farmer_database'
]
Models
Django uses classes called “models” for information. To draw a parallel to something like SQL or tables, the properties of the models correspond to column titles.
For my farmer database, I needed a few models: a farmer model, a product model, and a linking model to connect products to the farmers that have that product.
- The farmer model needs the farmer’s name, an address they can be found at, and an ID.
- The product model needs the product type (ex.: carrots) and an ID
- The link table then takes each instance of a product and links it to the farmer that has that product and the product type, via their IDs. We can also give it its own ID.
This is entered into the models.py
file inside the app directory (farmer_database
). Make sure the models
module is imported from the django
package.
from django.db import models# Models
class Farmer(models.Model):
farmer_id = models.IntegerField()
name = models.CharField(max_length=256)
address = models.CharField(max_length=256)class Product(models.Model):
product_id = models.IntegerField()
product_type = models.CharField(max_length=256)class FPLink(models.Model):
instance_id = models.IntegerField()
farmer_id = models.IntegerField()
product_id = models.IntegerField()`
We then use manage.py
to update the database to include these models with migrations.
First, we make the migrations:
$ python manage.py makemigrations farmer_datebase
Then we apply them to the SQL database (by default, this is SQLite):
$ python manage.py migrate
Setting up the REST framework
To make this database accessible online, we need a REST framework. For this, we can use Django’s REST framework. Since our Android app will be using JSON format, you can implement this with JSON:API support — a specification for building APIs in JSON with a standardized format.
First, install the necessary packages:
$ pip install djangorestframework
$ pip install djangorestframework-jsonapi
$ pip install django-filter
Add ‘rest_framework’
and ‘rest_framework_json_api’
to your INSTALLED_APPS settings:
INSTALLED_APPS = [
...,
'farmer_database',
'rest_framework',
'rest_framework_json_api'
]
Then, from the documentation, find the Settings segment and copy the REST_FRAMEWORK code to the end of your settings.py
file. This will ensure the REST framework follows the JSON:API format.
Serializers
Now that we have our framework and models, we need to communicate the models to the framework. This is done with serializers. Create a serializers.py
file in your app directory (database_farmers).
In this file, import serializers from the JSON:API framework and the defined models from your app:
from rest_framework_json_api import serializers
from farmer_database.models import Farmer, Product, FPLink
Then, define your serializer class with a meta class that has two fields: the model and its fields as a tuple.
class FarmerSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Farmer
fields = (‘farmer_id’, ‘name’, ‘address’)class ProductSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Product
fields = (‘product_id’, ‘product_type’)class FPLinkSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = FPLink
fields = (‘instance_id’, ‘farmer_id’, ‘product_id’)
Views and URLs
We now have to give the framework the views and paths for the HTTP requests.
The app directory already has a views.py
file, which contains the viewset classes needed for this. However, since we’re using JSON:API, we’ll take a different approach from the boilerplate code in the file. Delete the existing code and instead import the new rest framework.
You also need to import your models and serializers.
from farmer_database.models import Farmer, Product, FPLink
from farmer_database.serializers import FarmerSerializer, ProductSerializer, FPLinkSerializer
from rest_framework import viewsets
Then, define the classes for each model. The fields will be a “QuerySet,” Django’s database-abstraction tool (a collection of objects from the models, much like SELECT
in SQL) and the corresponding serializer:
class FarmerViewSet(viewsets.ModelViewSet):
queryset = Farmer.objects.all()
serializer_class = FarmerSerializerclass ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializerclass FPLinkViewSet(viewsets.ModelViewSet):
queryset = FPLink.objects.all()
serializer_class = FPLinkSerializer
Now, we define the URLs to access the models. This can be done in the package directory farmer_database_app
in the urls.py
file. Here we connect the URL paths to the corresponding viewsets, so we need to import the necessary URL tools, our rest framework tools, and our viewsets.
from django.urls import include, path
from rest_framework import routers
from farmer_database import views
Then, define your URL patterns:
router = routers.DefaultRouter()
router.register(r'farmers', views.FarmerViewSet)
router.register(r'products', views.ProductViewSet)
router.register(r'fplinks', views.FPLinkViewSet)urlpatterns = [
path('', include(router.urls))
]
This creates GET, POST, PATCH and DELETE methods for all of our models.
I’ll go over how to start and test the server in the next tutorial!