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
Larry Cai
 
PPTX
REST Easy with Django-Rest-Framework
Marcel Chastain
 
PDF
Web develop in flask
Jim Yeh
 
PDF
Let's read code: the python-requests library
Susan Tan
 
PPTX
Restful api
Anurag Srivastava
 
PPTX
Django - Python MVC Framework
Bala Kumar
 
PPTX
Automate using Python
YogeshIngale9
 
PDF
Django interview Questions| Edureka
Edureka!
 
Learn REST API with Python
Larry Cai
 
REST Easy with Django-Rest-Framework
Marcel Chastain
 
Web develop in flask
Jim Yeh
 
Let's read code: the python-requests library
Susan Tan
 
Restful api
Anurag Srivastava
 
Django - Python MVC Framework
Bala Kumar
 
Automate using Python
YogeshIngale9
 
Django interview Questions| Edureka
Edureka!
 

What's hot (20)

PPTX
JSON: The Basics
Jeff Fox
 
PPTX
Angular modules in depth
Christoffer Noring
 
PPTX
Json
Steve Fort
 
PPTX
React js
Oswald Campesato
 
PDF
Django Introduction & Tutorial
之宇 趙
 
PPTX
Full stack development
Arnav Gupta
 
PDF
An introduction to MongoDB
Universidade de São Paulo
 
PPTX
Natural Language processing using nltk.pptx
Ramakrishna Reddy Bijjam
 
PPT
Introduction to PHP
Jussi Pohjolainen
 
PPT
Django
Kangjin Jun
 
PDF
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Edureka!
 
PPTX
Flask
Mamta Kumari
 
PDF
Python Collections Tutorial | Edureka
Edureka!
 
PDF
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
PPTX
Node.js Express
Eyal Vardi
 
ODP
Django for Beginners
Jason Davies
 
PDF
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Edureka!
 
PPTX
Web development with django - Basics Presentation
Shrinath Shenoy
 
PPTX
Intro to React
Justin Reock
 
JSON: The Basics
Jeff Fox
 
Angular modules in depth
Christoffer Noring
 
Django Introduction & Tutorial
之宇 趙
 
Full stack development
Arnav Gupta
 
An introduction to MongoDB
Universidade de São Paulo
 
Natural Language processing using nltk.pptx
Ramakrishna Reddy Bijjam
 
Introduction to PHP
Jussi Pohjolainen
 
Django
Kangjin Jun
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Edureka!
 
Python Collections Tutorial | Edureka
Edureka!
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Node.js Express
Eyal Vardi
 
Django for Beginners
Jason Davies
 
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Edureka!
 
Web development with django - Basics Presentation
Shrinath Shenoy
 
Intro to React
Justin Reock
 
Ad

Viewers also liked (20)

PDF
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future
 
PDF
Building Automated REST APIs with Python
Jeff Knupp
 
PDF
Developing RESTful Web APIs with Python, Flask and MongoDB
Nicola Iarocci
 
PDF
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Innovecs
 
PPTX
Flask – Python
Max Claus Nunes
 
PPTX
DEVNET-1001 Coding 101: How to Call REST APIs from a REST Client and Python
Cisco DevNet
 
PDF
RESTful API Design, Second Edition
Apigee | Google Cloud
 
PPTX
JSON and REST
Robert MacLean
 
PDF
Python tools for testing web services over HTTP
Mykhailo Kolesnyk
 
PDF
Building a Dynamic Website Using Django
Nathan Eror
 
PDF
Filling the flask
Jason Myers
 
KEY
Quattro passi tra le nuvole (e non scordate il paracadute)
Nicola Iarocci
 
KEY
Fuga dalla Comfort Zone
Nicola Iarocci
 
PDF
CoderDojo Romagna
Nicola Iarocci
 
PPTX
Hands on django part 1
MicroPyramid .
 
PDF
Intro python-object-protocol
Shiyao Ma
 
PDF
Diabetes and Me: My Journey So Far
Jason Myers
 
ODP
An Introduction to REDIS NoSQL database
Ali MasudianPour
 
PDF
Python Static Analysis Tools
Jason Myers
 
PDF
Online / Offline
Nicola Iarocci
 
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future
 
Building Automated REST APIs with Python
Jeff Knupp
 
Developing RESTful Web APIs with Python, Flask and MongoDB
Nicola Iarocci
 
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Innovecs
 
Flask – Python
Max Claus Nunes
 
DEVNET-1001 Coding 101: How to Call REST APIs from a REST Client and Python
Cisco DevNet
 
RESTful API Design, Second Edition
Apigee | Google Cloud
 
JSON and REST
Robert MacLean
 
Python tools for testing web services over HTTP
Mykhailo Kolesnyk
 
Building a Dynamic Website Using Django
Nathan Eror
 
Filling the flask
Jason Myers
 
Quattro passi tra le nuvole (e non scordate il paracadute)
Nicola Iarocci
 
Fuga dalla Comfort Zone
Nicola Iarocci
 
CoderDojo Romagna
Nicola Iarocci
 
Hands on django part 1
MicroPyramid .
 
Intro python-object-protocol
Shiyao Ma
 
Diabetes and Me: My Journey So Far
Jason Myers
 
An Introduction to REDIS NoSQL database
Ali MasudianPour
 
Python Static Analysis Tools
Jason Myers
 
Online / Offline
Nicola Iarocci
 
Ad

Similar to Rest api with Python (20)

PPTX
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
Caktus Group
 
PPTX
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
Caktus Group
 
PDF
Django Restful Web Services Gaston C Hillar
suilahvrieze
 
PDF
Building an API with Django and Django REST Framework
Christopher Foresman
 
PDF
Django Rest Framework - Building a Web API
Marcos Pereira
 
PPTX
Django with REST API Online Training - NareshIT
avinashnit
 
PDF
Building RESTful APIs
Silota Inc.
 
PPTX
Django REST Framework 2022fffffffff.pptx
ThirzaAhmadTsaqif
 
PDF
UnRESTful APIs with Django
Ari Lacenski
 
PDF
Rest apis with DRF
Dharmit Shah
 
PPTX
Introduction to Django Rest Framework
bangaloredjangousergroup
 
PPTX
Drf
Ibrahim Kasim
 
PDF
API Design & Security in django
Tareque Hossain
 
PDF
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Nina Zakharenko
 
PDF
Django REST Framework
Load Impact
 
PDF
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Inexture Solutions
 
PDF
Django Rest Framework + React
wsvincent
 
PDF
DRF React
wsvincent
 
PPTX
React django
Heber Silva
 
PDF
REST in pieces
sparkfabrik
 
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
Caktus Group
 
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
Caktus Group
 
Django Restful Web Services Gaston C Hillar
suilahvrieze
 
Building an API with Django and Django REST Framework
Christopher Foresman
 
Django Rest Framework - Building a Web API
Marcos Pereira
 
Django with REST API Online Training - NareshIT
avinashnit
 
Building RESTful APIs
Silota Inc.
 
Django REST Framework 2022fffffffff.pptx
ThirzaAhmadTsaqif
 
UnRESTful APIs with Django
Ari Lacenski
 
Rest apis with DRF
Dharmit Shah
 
Introduction to Django Rest Framework
bangaloredjangousergroup
 
API Design & Security in django
Tareque Hossain
 
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Nina Zakharenko
 
Django REST Framework
Load Impact
 
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Inexture Solutions
 
Django Rest Framework + React
wsvincent
 
DRF React
wsvincent
 
React django
Heber Silva
 
REST in pieces
sparkfabrik
 

Recently uploaded (20)

PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
The Future of Artificial Intelligence (AI)
Mukul
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PPTX
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
PDF
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
The Future of Artificial Intelligence (AI)
Mukul
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
Doc9.....................................
SofiaCollazos
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 

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 !