Rest api with Python
-
Upload
santosh-ghimire -
Category
Technology
-
view
240 -
download
10
Transcript of Rest api with Python
Rest API with Python
Santosh GhimireCOO and Co-founder, Phunka Technologies
REST API
REpresentational State Transfer
Not a new concept
The concepts are as old as the web itself
Why REST?
Client-Server
Stateless
JSON, XML, etc.
GETPUTPOSTDELETE
Develop your API RESTful and go to rest….
REST with Python
REST API can be implemented with Python’s web frameworks.
Django, Flask, Tornado, Pyramid
REST API in Django
LibrariesDjango Rest Framework (DRF)Django-TastypieDjango-BracesRestless
Django Rest Framework
Package for Django
Views, authentication and utilities for building web APIs
Both highly configurable and low boilerplate
Installation$ pip install djangorestframework
$ python manage.py syncdb
# settings.py
INSTALLED_APPS = (
...
# third party apps
'rest_framework',
...
)
Basic Elements
Serializers
Views
Urls
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')
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,)
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)),
)
So, what’s the result?
Let’s add some stuffs
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.
Setting Permissions Globally# library/settings/base.py
...
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticatedOrReadOnly',
)
}
API Best Practices
Versioning
Clients are not generally updated
Typically handled by URL
VersioningrouterV1 = routers.DefaultRouter()
...
urlpatterns = patterns('',
url(r'^api/v1', include(routerV1.urls)),
)
Documentation
Plan your API first
Prepare documentation before you code
Testing
Your API is a promise to your fellow developers
Unit testing helps you keep your promises
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')
What about Non-ORM?
Yes ! DRF serialization supports non-ORM data sources.
REST API implemented with Mongodb and DRF in Meroanswer.
Further Reading● http://www.django-rest-framework.org/
● http://jacobian.org/writing/rest-worst-practices/
● http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
Santosh GhimireCOO and Co-founder, Phunka TechnologiesTwitter: @SantoshGhimireEmail: [email protected]
Thanks !