Slides: https://slides.com/danielmouris/zero-to-api/
Follow Live: https://slides.com/danielmouris/zero-to-api/live
Github Repository: https://github.com/dgmouris/zero_to_api
Who am I?
Who is this talk for?
What is a RESTful API?
What Python packages are we going to use?
Installing the packages needed
Building our RESTful API from scratch
a. Create a Django project and run itOutline
Who is this talk for?
What is a RESTful API?
What Python packages are we going to use?
Installing the packages needed
Building our RESTful API from scratch
a. Create a Django project and run itMarshmallow
Ghost
Gambit
Outline
Who am I?
What is a RESTful API?
What Python packages are we going to use?
Installing the packages needed
Building our RESTful API from scratch
a. Create a Django project and run itIf you want learn more about but aren't fully familiar with:
then this talk is for you.
If you are already familiar with all of this, please try to help (and /or sit beside) your friends who may not be as familiar with the above.
Python 3.6+
Acronym for Application Programmer Interface.
Stands for REpresentational State Transfer.
A URL of an/our API. ie. http://localhost:8000/rest-auth/login/
The code interface that Django uses to interact with the database.
A way that Django uses code to create database tables for our project.
The computer that is making the calls to the API.
A model does two things, first it is a class that maps fields to columns in a table. Secondly, it provides a Python interface to the database to get, create, update, and delete data.
Type of class based view; automatically generates the URL endpoints to get, create, update & delete data if used within a router.
This allows us to convert Python datatypes to json, and json back to a Python datatype while validating the data.
Outline
Who am I?
Who is this talk for?
What Python packages are we going to use?
Installing the packages needed
Building our RESTful API from scratch
a. Create a Django project and run itIt's a way to ask for, modify, create , and delete data on another computer or server over the web.
It's also a way that you can trigger an action on a server (such as what anyone here uses Python for) and getting a result.
Do you have cats?
1. Ask if I have cats.
Air between us
Me
You
2. I'll respond to tell you that I do have cats
I have three cute cats
Note:
I'll only tell people I have three cats if I trust them. Otherwise I won't tell them.
Air between us
Server
Serving API
- Mobile App
- Other Server
- Front End
GET /cats/
This will be sent with a token to show that we can trust the client (I'll cover that later).
The Internet
Server
Serving API
- Mobile App
- Other Server
- Front End
Status 200
Body: Cat Names
If the token is correct, we'll give them the information.
The Internet
Outline
Who am I?
Who is this talk for?
What is a RESTful API?
Installing the packages needed
Building our RESTful API from scratch
a. Create a Django project and run it1. Django
- Web Framework, Server, Object Relational Mapper (ORM)
https://www.djangoproject.com/
2. Django Rest Framework (DRF)
- Package for Django to create RESTful APIs
https://www.django-rest-framework.org/
3. Django Rest Auth
- Package for DRF for authentication
https://django-rest-auth.readthedocs.io/en/latest/
Outline
Who am I?
Who is this talk for?
What is a RESTful API?
What Python packages are we going to use?
Building our RESTful API from scratch
a. Create a Django project and run itCreate a directory that you're going to use for the project:
mkdir <your-project-name>
cd <your-project-name>
Create an isolated Python environment:
pipenv shell --python 3.6
With Pipenv, install all of the packages we just talked about:
pipenv install django
pipenv install djangorestframework
pipenv install django-rest-auth
Now we can use these packages in our Django project that we're going to create!
Outline
Who am I?
Who is this talk for?
What is a RESTful API?
What Python packages are we going to use?
Installing the packages needed
Go into your project and start your virtual environment (using Pipenv shell):
cd <your-project-name>
pipenv shell
Let's create a Django project from Django's command line tool:
django-admin.py startproject <your_project_name>
Go into your project (below) and we'll talk about what's there:
cd <your_project_name>
Let's see what's in the Django project:
Let's see what's in the folder of the same name as our project:
Let's run our server (you are in the same folder as manage.py):
python manage.py runserver
Your terminal should show something like this:
You should see something like:
"The install worked successfully! Congratulations!"
Since the project is telling us we have unapplied migrations, let's apply them:
python manage.py migrate
Django has an ORM which allows us to access and modify the database.
Applying migrations is a mechanism that Django gives us to create, modify and add tables to the database.
python manage.py runserver
Let's run our server again: (no migration warnings!)
Outline
Who am I?
Who is this talk for?
What is a RESTful API?
What Python packages are we going to use?
Installing the packages needed
Within your Django project open <your-projectname>/settings.py
and add the following lines to the INSTALLED_APPS list:
# my installed apps
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
Now if you run your server again, you'll see that there are unapplied migrations (new tables from our packages) that need to be applied.
Follow the steps previously defined to apply these migrations:
python manage.py migrate
Should look like this:
Open your <project-name>/urls.py file and add the following import:
from django.contrib import admin
from django.conf.urls import url, include
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^rest-auth/', include('rest_auth.urls')),
]
url(r'^rest-auth/', include('rest_auth.urls')),
Add the line to url_patterns:
from django.conf.urls import url, include
Let's run our server (you are in the same folder as manage.py):
python manage.py runserver
Go to your browser and you'll see a 404 error. Some URL patterns are defined:
Outline
Who am I?
Who is this talk for?
What is a RESTful API?
What Python packages are we going to use?
Installing the packages needed
Go into the root directory of your project. Write the following in order to create a super user:
python manage.py createsuperuser
Answer the questions that follow (basically username, email, and password).
The response should be successful, with a key as the response:
Outline
Who am I?
Who is this talk for?
What is a RESTful API?
What Python packages are we going to use?
Installing the packages needed
An app is a logical unit for your site.
We're going to create a Django "app" within the project and add it to our project:
python manage.py startapp cats
Add this "app" to our INSTALLED_APPS in our
<project-name>/settings.py file (in the INSTALLED_APPS list):
'cats',
Open the cats/models.py file and add the following lines:
from django.db import models
class CatType(models.Model):
type_name = models.CharField(max_length=255)
description = models.CharField(max_length=255)
def __str__(self):
return "{}, {}".format(self.type_name, self.description)
class Cat(models.Model):
name = models.CharField(max_length=255)
cat_type = models.ForeignKey(CatType,
on_delete=models.SET_NULL,
null=True)
def __str__(self):
return "{}, {}".format(self.name, self.cat_type)
Models are the way you define tables in your database in Django. It's also the way that you interact with your database to get, create, update and delete data.
Open your terminal and make the migrations:
python manage.py makemigrations
Let's apply the migrations to our database so that we can use those models:
python manage.py migrate
This will create some changes because we modified our cats/models.py file.
In the cats/admin.py file, add the following lines:
from django.contrib import admin
from cats.models import Cat, CatType
class CatAdmin(admin.ModelAdmin):
pass
admin.site.register(Cat, CatAdmin)
class CatTypeAdmin(admin.ModelAdmin):
pass
admin.site.register(CatType, CatTypeAdmin)
Django gives us an admin dashboard where we can add data to our tables and see our data. To do this, we need to "register" our models with Django's admin.
Open your browser and go to the admin!
Once you open the admin, login with the credentials created earlier.
from rest_framework import serializers
from cats.models import Cat, CatType
class CatTypeSerializer(serializers.ModelSerializer):
class Meta:
model = CatType
fields = '__all__'
class CatSerializer(serializers.ModelSerializer):
class Meta:
model = Cat
fields = '__all__'
depth = 1
Serializers translate Python datatypes and models into json.
Serializers also allow us to translate json data back into Python and also give the ability for validation.
We use a model serializer to simplify the code.
Let's create a cats/serializers.py file by adding the following:
from django.shortcuts import render
from rest_framework import viewsets
from cats.models import Cat, CatType
from cats.serializers import CatTypeSerializer, CatSerializer
class CatTypeViewSet(viewsets.ModelViewSet):
queryset = CatType.objects.all()
serializer_class = CatTypeSerializer
class CatViewSet(viewsets.ModelViewSet):
queryset = Cat.objects.all()
serializer_class = CatSerializer
Viewsets are very similar to views in Django. This is the the code that gets executed when you do a GET or POST request.
We're using a ModelViewset to simplify what we're doing.
Let's add the following to the cats/views.py file:
from django.conf.urls import url
from rest_framework import routers
from cats.views import CatTypeViewSet, CatViewSet
router = routers.DefaultRouter()
router.register(r'cat-types', CatTypeViewSet)
router.register(r'cats', CatViewSet)
urlpatterns = router.urls
Let's create a cats/urls.py file and add the following code to the file:
We are going to add a "router" which adds the logic to handle the requests and point them to the right class.
from django.contrib import admin
from django.conf.urls import url, include
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^rest-auth/', include('rest_auth.urls')),
url(r'^cats/', include('cats.urls')),
]
Open <project-name>/urls.py and add the following line in the url_patterns list:
Find the URLs from our defined app and add them to your project.
url(r'^cats/', include('cats.urls')),
The overall file should look like this:
You can browse your own API.
You'll get a CSRF token failure.....
Let's continue and get this done!
Outline
Who am I?
Who is this talk for?
What is a RESTful API?
What Python packages are we going to use?
Installing the packages needed
Since you won't be having any javascript on your page, we're going to use token authentication to login.
Let's make our settings reflect this!
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'PAGE_SIZE': 100,
}
Open <project-name>/settings.py and add the following lines:
This tells the API to use tokens instead of a session which is what we need if we want to make an authenticated app.
from django.shortcuts import render
from rest_framework import viewsets, permissions
from cats.models import Cat, CatType
from cats.serializers import CatTypeSerializer, CatSerializer
class CatTypeViewSet(viewsets.ModelViewSet):
permission_classes = [permissions.IsAuthenticated]
queryset = CatType.objects.all()
serializer_class = CatTypeSerializer
class CatViewSet(viewsets.ModelViewSet):
permission_classes = [permissions.IsAuthenticated]
queryset = Cat.objects.all()
serializer_class = CatSerializer
Open your cats/views.py file.
Add permissions as an import and add the permissions classes to each serializer:
Fill in your RESTful API client with the following information:
We just confirmed that we need to be authenticated to view our cats!
The response of the above request should give you a successful request:
Save this token to a text file.
In the Headers section, add an "Authorization" header with the value of "Token <your saved token here>".
A successful response is given using the authentication token! Great!
Marshmallow
Ghost
Gambit