SlideShare a Scribd company logo
Rest API with Python
Santosh Ghimire
COO 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.
GET
PUT
POST
DELETE
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
Libraries
Django Rest Framework (DRF)
Django-Tastypie
Django-Braces
Restless
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
Serializers
from 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')
Views
from 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,)
Urls
from 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?
Rest api with Python
Rest api with Python
Rest api with Python
Let’s add some stuffs
Rest api with Python
CSRF Protection
Ensure 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
Versioning
routerV1 = 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
Testing
from 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 Ghimire
COO and Co-founder, Phunka Technologies
Twitter: @SantoshGhimire
Email: santosh@phunka.com
Thanks !

More Related Content

PPT
Learn REST API with Python
PDF
Let's read code: the python-requests library
PPTX
REST Easy with Django-Rest-Framework
PDF
Web develop in flask
PPTX
Django - Python MVC Framework
PDF
Quick flask an intro to flask
PPTX
Automate using Python
PPTX
Restful api
Learn REST API with Python
Let's read code: the python-requests library
REST Easy with Django-Rest-Framework
Web develop in flask
Django - Python MVC Framework
Quick flask an intro to flask
Automate using Python
Restful api

What's hot (20)

PPTX
Php.ppt
PDF
Lesson 03 python statement, indentation and comments
PPT
PHP POWERPOINT SLIDES
PPSX
Php and MySQL
PPT
Introduction to Web Programming - first course
PDF
Introduction to flutter
PPTX
Namespaces in C#
PPTX
Introduction to xampp
PPT
MySQL Functions
PPT
SQLITE Android
PPTX
SQLite database in android
PPTX
Operators php
PDF
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
PPT
MYSQL - PHP Database Connectivity
PPTX
virtual hosting and configuration
PPS
RIA and Ajax
PDF
Data Types In PHP
PDF
Command line-arguments-in-java-tutorial
PPTX
Introduction to ASP.NET
PPTX
Java Queue.pptx
Php.ppt
Lesson 03 python statement, indentation and comments
PHP POWERPOINT SLIDES
Php and MySQL
Introduction to Web Programming - first course
Introduction to flutter
Namespaces in C#
Introduction to xampp
MySQL Functions
SQLITE Android
SQLite database in android
Operators php
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
MYSQL - PHP Database Connectivity
virtual hosting and configuration
RIA and Ajax
Data Types In PHP
Command line-arguments-in-java-tutorial
Introduction to ASP.NET
Java Queue.pptx
Ad

Viewers also liked (20)

PDF
Python RESTful webservices with Python: Flask and Django solutions
PDF
Building Automated REST APIs with Python
PDF
Developing RESTful Web APIs with Python, Flask and MongoDB
PDF
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
PPTX
Flask – Python
PPTX
DEVNET-1001 Coding 101: How to Call REST APIs from a REST Client and Python
PDF
RESTful API Design, Second Edition
PPTX
JSON and REST
PDF
Python tools for testing web services over HTTP
PDF
Building a Dynamic Website Using Django
PDF
Filling the flask
KEY
Quattro passi tra le nuvole (e non scordate il paracadute)
KEY
Fuga dalla Comfort Zone
PDF
CoderDojo Romagna
PPTX
Hands on django part 1
PDF
Intro python-object-protocol
PDF
Diabetes and Me: My Journey So Far
ODP
An Introduction to REDIS NoSQL database
PDF
Python Static Analysis Tools
PDF
Online / Offline
Python RESTful webservices with Python: Flask and Django solutions
Building Automated REST APIs with Python
Developing RESTful Web APIs with Python, Flask and MongoDB
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Flask – Python
DEVNET-1001 Coding 101: How to Call REST APIs from a REST Client and Python
RESTful API Design, Second Edition
JSON and REST
Python tools for testing web services over HTTP
Building a Dynamic Website Using Django
Filling the flask
Quattro passi tra le nuvole (e non scordate il paracadute)
Fuga dalla Comfort Zone
CoderDojo Romagna
Hands on django part 1
Intro python-object-protocol
Diabetes and Me: My Journey So Far
An Introduction to REDIS NoSQL database
Python Static Analysis Tools
Online / Offline
Ad

Similar to Rest api with Python (20)

PPTX
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
PPTX
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
PDF
Django Restful Web Services Gaston C Hillar
PDF
Building an API with Django and Django REST Framework
PDF
Django Rest Framework - Building a Web API
PPTX
Django with REST API Online Training - NareshIT
PDF
Building RESTful APIs
PPTX
Django REST Framework 2022fffffffff.pptx
PDF
UnRESTful APIs with Django
PDF
Rest apis with DRF
PPTX
Introduction to Django Rest Framework
PPTX
PDF
API Design & Security in django
PDF
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
PDF
Django REST Framework
PDF
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
PDF
Django Rest Framework + React
PDF
DRF React
PPTX
React django
PDF
REST in pieces
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
Django Restful Web Services Gaston C Hillar
Building an API with Django and Django REST Framework
Django Rest Framework - Building a Web API
Django with REST API Online Training - NareshIT
Building RESTful APIs
Django REST Framework 2022fffffffff.pptx
UnRESTful APIs with Django
Rest apis with DRF
Introduction to Django Rest Framework
API Design & Security in django
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Django REST Framework
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Django Rest Framework + React
DRF React
React django
REST in pieces

Recently uploaded (20)

PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Advanced IT Governance
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PPTX
Cloud computing and distributed systems.
PPTX
Spectroscopy.pptx food analysis technology
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Empathic Computing: Creating Shared Understanding
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
cuic standard and advanced reporting.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Electronic commerce courselecture one. Pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Spectral efficient network and resource selection model in 5G networks
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Advanced IT Governance
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
GamePlan Trading System Review: Professional Trader's Honest Take
Understanding_Digital_Forensics_Presentation.pptx
madgavkar20181017ppt McKinsey Presentation.pdf
Cloud computing and distributed systems.
Spectroscopy.pptx food analysis technology
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Chapter 3 Spatial Domain Image Processing.pdf
Review of recent advances in non-invasive hemoglobin estimation
Empathic Computing: Creating Shared Understanding
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
cuic standard and advanced reporting.pdf
Network Security Unit 5.pdf for BCA BBA.
Electronic commerce courselecture one. Pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy

Rest api with Python

  • 1. Rest API with Python Santosh Ghimire COO and Co-founder, Phunka Technologies
  • 2. REST API REpresentational State Transfer Not a new concept The concepts are as old as the web itself
  • 4. Develop your API RESTful and go to rest….
  • 5. REST with Python REST API can be implemented with Python’s web frameworks. Django, Flask, Tornado, Pyramid
  • 6. REST API in Django Libraries Django Rest Framework (DRF) Django-Tastypie Django-Braces Restless
  • 7. Django Rest Framework Package for Django Views, authentication and utilities for building web APIs Both highly configurable and low boilerplate
  • 8. Installation $ pip install djangorestframework $ python manage.py syncdb # settings.py INSTALLED_APPS = ( ... # third party apps 'rest_framework', ... )
  • 10. Serializers from 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')
  • 11. Views from 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,)
  • 12. Urls from 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)), )
  • 13. So, what’s the result?
  • 19. CSRF Protection Ensure 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.
  • 20. Setting Permissions Globally # library/settings/base.py ... REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ) }
  • 22. Versioning Clients are not generally updated Typically handled by URL
  • 23. Versioning routerV1 = routers.DefaultRouter() ... urlpatterns = patterns('', url(r'^api/v1', include(routerV1.urls)), )
  • 24. Documentation Plan your API first Prepare documentation before you code
  • 25. Testing Your API is a promise to your fellow developers Unit testing helps you keep your promises
  • 26. Testing from 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')
  • 27. What about Non-ORM? Yes ! DRF serialization supports non-ORM data sources. REST API implemented with Mongodb and DRF in Meroanswer.
  • 28. 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
  • 29. Santosh Ghimire COO and Co-founder, Phunka Technologies Twitter: @SantoshGhimire Email: [email protected] Thanks !