rest api with python

29
Rest API with Python Santosh Ghimire COO and Co-founder, Phunka Technologies

Upload: santosh-ghimire

Post on 15-Jul-2015

262 views

Category:

Technology


10 download

TRANSCRIPT

Page 1: Rest api with Python

Rest API with Python

Santosh GhimireCOO and Co-founder, Phunka Technologies

Page 2: Rest api with Python

REST API

REpresentational State Transfer

Not a new concept

The concepts are as old as the web itself

Page 3: Rest api with Python

Why REST?

Client-Server

Stateless

JSON, XML, etc.

GETPUTPOSTDELETE

Page 4: Rest api with Python

Develop your API RESTful and go to rest….

Page 5: Rest api with Python

REST with Python

REST API can be implemented with Python’s web frameworks.

Django, Flask, Tornado, Pyramid

Page 6: Rest api with Python

REST API in Django

LibrariesDjango Rest Framework (DRF)Django-TastypieDjango-BracesRestless

Page 7: Rest api with Python

Django Rest Framework

Package for Django

Views, authentication and utilities for building web APIs

Both highly configurable and low boilerplate

Page 8: Rest api with Python

Installation$ pip install djangorestframework

$ python manage.py syncdb

# settings.py

INSTALLED_APPS = (

...

# third party apps

'rest_framework',

...

)

Page 9: Rest api with Python

Basic Elements

Serializers

Views

Urls

Page 10: Rest api with Python

Serializersfrom rest_framework import serializers

from .models import Book, Author

class BookSerializer(serializers.HyperlinkedModelSerializer):

class Meta:

model = Book

fields = ('name', 'price', 'category', 'url')

class AuthorSerializer(serializers.HyperlinkedModelSerializer):

class Meta:

model = Author

fields = ('name', 'creations', 'url')

Page 11: Rest api with Python

Viewsfrom rest_framework import viewsets, permissions

from .models import Book, Author

from .serializers import BookSerializer, AuthorSerializer

class BookViewSet(viewsets.ModelViewSet):

""" API endpoint that allows books in the library to be viewed or edited """

queryset = Book.objects.all()

serializer_class = BookSerializer

class AuthorViewSet(viewsets.ModelViewSet):

""" API endpoint that allows Authors details to be viewed or edited """

queryset = Author.objects.all()

serializer_class = AuthorSerializer

permission_classes = (permissions.IsAuthenticated,)

Page 12: Rest api with Python

Urlsfrom django.conf.urls import patterns, include, url

from django.contrib import admin

from rest_framework import routers

from book import views

router = routers.DefaultRouter()

router.register(r'book', views.BookViewSet)

router.register(r'authors', views.AuthorViewSet)

admin.autodiscover()

urlpatterns = patterns( '',

url(r'^', include(router.urls)),

url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),

# Django admin

url(r'^admin/', include(admin.site.urls)),

)

Page 13: Rest api with Python

So, what’s the result?

Page 14: Rest api with Python
Page 15: Rest api with Python
Page 16: Rest api with Python
Page 17: Rest api with Python

Let’s add some stuffs

Page 18: Rest api with Python
Page 19: Rest api with Python

CSRF ProtectionEnsure that the 'safe' HTTP operations, such as GET, HEAD and OPTIONS can’t be used to alter any server-side state.

Ensure that any 'unsafe' HTTP operations, such as POST, PUT, PATCH and DELETE, always require a valid CSRF token.

Page 20: Rest api with Python

Setting Permissions Globally# library/settings/base.py

...

REST_FRAMEWORK = {

'DEFAULT_PERMISSION_CLASSES': (

'rest_framework.permissions.IsAuthenticatedOrReadOnly',

)

}

Page 21: Rest api with Python

API Best Practices

Page 22: Rest api with Python

Versioning

Clients are not generally updated

Typically handled by URL

Page 23: Rest api with Python

VersioningrouterV1 = routers.DefaultRouter()

...

urlpatterns = patterns('',

url(r'^api/v1', include(routerV1.urls)),

)

Page 24: Rest api with Python

Documentation

Plan your API first

Prepare documentation before you code

Page 25: Rest api with Python

Testing

Your API is a promise to your fellow developers

Unit testing helps you keep your promises

Page 26: Rest api with Python

Testingfrom rest_framework.test import APITestCase

from .models import Book

class BookTestCase(APITestCase):

def setUp(self):

book1 = Book.objects.create(

name='Eleven Minutes',

price=2000,

category='literature'

)

def test_get_books(self):

response = self.client.get('/book/', format='json')

self.assertEqual(response.data[0]['name'], u'Eleven Minutes')

Page 27: Rest api with Python

What about Non-ORM?

Yes ! DRF serialization supports non-ORM data sources.

REST API implemented with Mongodb and DRF in Meroanswer.

Page 29: Rest api with Python

Santosh GhimireCOO and Co-founder, Phunka TechnologiesTwitter: @SantoshGhimireEmail: [email protected]

Thanks !