SlideShare a Scribd company logo
1 of 29
Download to read offline
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?
Let’s add some stuffs
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

What's hot (20)

Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 
Web develop in flask
Web develop in flaskWeb develop in flask
Web develop in flask
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
Expressjs
ExpressjsExpressjs
Expressjs
 
Introduction To PHP
Introduction To PHPIntroduction To PHP
Introduction To PHP
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
 
An introduction to MongoDB
An introduction to MongoDBAn introduction to MongoDB
An introduction to MongoDB
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
Flask
FlaskFlask
Flask
 
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop Notes
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Django - Python MVC Framework
Django - Python MVC FrameworkDjango - Python MVC Framework
Django - Python MVC Framework
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
 
Express js
Express jsExpress js
Express js
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 

Viewers also liked

Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsSolution4Future
 
Building Automated REST APIs with Python
Building Automated REST APIs with PythonBuilding Automated REST APIs with Python
Building Automated REST APIs with PythonJeff Knupp
 
Developing RESTful Web APIs with Python, Flask and MongoDB
Developing RESTful Web APIs with Python, Flask and MongoDBDeveloping RESTful Web APIs with Python, Flask and MongoDB
Developing RESTful Web APIs with Python, Flask and MongoDBNicola Iarocci
 
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...Innovecs
 
DEVNET-1001 Coding 101: How to Call REST APIs from a REST Client and Python
DEVNET-1001 Coding 101: How to Call REST APIs from a REST Client and PythonDEVNET-1001 Coding 101: How to Call REST APIs from a REST Client and Python
DEVNET-1001 Coding 101: How to Call REST APIs from a REST Client and PythonCisco DevNet
 
Python tools for testing web services over HTTP
Python tools for testing web services over HTTPPython tools for testing web services over HTTP
Python tools for testing web services over HTTPMykhailo Kolesnyk
 
Building a Dynamic Website Using Django
Building a Dynamic Website Using DjangoBuilding a Dynamic Website Using Django
Building a Dynamic Website Using DjangoNathan Eror
 
Filling the flask
Filling the flaskFilling the flask
Filling the flaskJason Myers
 
Quattro passi tra le nuvole (e non scordate il paracadute)
Quattro passi tra le nuvole (e non scordate il paracadute)Quattro passi tra le nuvole (e non scordate il paracadute)
Quattro passi tra le nuvole (e non scordate il paracadute)Nicola Iarocci
 
Fuga dalla Comfort Zone
Fuga dalla Comfort ZoneFuga dalla Comfort Zone
Fuga dalla Comfort ZoneNicola Iarocci
 
Hands on django part 1
Hands on django part 1Hands on django part 1
Hands on django part 1MicroPyramid .
 
Intro python-object-protocol
Intro python-object-protocolIntro python-object-protocol
Intro python-object-protocolShiyao Ma
 
Diabetes and Me: My Journey So Far
Diabetes and Me: My Journey So FarDiabetes and Me: My Journey So Far
Diabetes and Me: My Journey So FarJason Myers
 
An Introduction to REDIS NoSQL database
An Introduction to REDIS NoSQL databaseAn Introduction to REDIS NoSQL database
An Introduction to REDIS NoSQL databaseAli MasudianPour
 
Python Static Analysis Tools
Python Static Analysis ToolsPython Static Analysis Tools
Python Static Analysis ToolsJason Myers
 
Introduction to SQLAlchemy and Alembic Migrations
Introduction to SQLAlchemy and Alembic MigrationsIntroduction to SQLAlchemy and Alembic Migrations
Introduction to SQLAlchemy and Alembic MigrationsJason Myers
 

Viewers also liked (20)

Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
 
Building Automated REST APIs with Python
Building Automated REST APIs with PythonBuilding Automated REST APIs with Python
Building Automated REST APIs with Python
 
Developing RESTful Web APIs with Python, Flask and MongoDB
Developing RESTful Web APIs with Python, Flask and MongoDBDeveloping RESTful Web APIs with Python, Flask and MongoDB
Developing RESTful Web APIs with Python, Flask and MongoDB
 
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
 
DEVNET-1001 Coding 101: How to Call REST APIs from a REST Client and Python
DEVNET-1001 Coding 101: How to Call REST APIs from a REST Client and PythonDEVNET-1001 Coding 101: How to Call REST APIs from a REST Client and Python
DEVNET-1001 Coding 101: How to Call REST APIs from a REST Client and Python
 
RESTful API Design, Second Edition
RESTful API Design, Second EditionRESTful API Design, Second Edition
RESTful API Design, Second Edition
 
JSON and REST
JSON and RESTJSON and REST
JSON and REST
 
Python tools for testing web services over HTTP
Python tools for testing web services over HTTPPython tools for testing web services over HTTP
Python tools for testing web services over HTTP
 
Building a Dynamic Website Using Django
Building a Dynamic Website Using DjangoBuilding a Dynamic Website Using Django
Building a Dynamic Website Using Django
 
Filling the flask
Filling the flaskFilling the flask
Filling the flask
 
Quattro passi tra le nuvole (e non scordate il paracadute)
Quattro passi tra le nuvole (e non scordate il paracadute)Quattro passi tra le nuvole (e non scordate il paracadute)
Quattro passi tra le nuvole (e non scordate il paracadute)
 
Fuga dalla Comfort Zone
Fuga dalla Comfort ZoneFuga dalla Comfort Zone
Fuga dalla Comfort Zone
 
CoderDojo Romagna
CoderDojo RomagnaCoderDojo Romagna
CoderDojo Romagna
 
Hands on django part 1
Hands on django part 1Hands on django part 1
Hands on django part 1
 
Intro python-object-protocol
Intro python-object-protocolIntro python-object-protocol
Intro python-object-protocol
 
Diabetes and Me: My Journey So Far
Diabetes and Me: My Journey So FarDiabetes and Me: My Journey So Far
Diabetes and Me: My Journey So Far
 
An Introduction to REDIS NoSQL database
An Introduction to REDIS NoSQL databaseAn Introduction to REDIS NoSQL database
An Introduction to REDIS NoSQL database
 
Python Static Analysis Tools
Python Static Analysis ToolsPython Static Analysis Tools
Python Static Analysis Tools
 
Online / Offline
Online / OfflineOnline / Offline
Online / Offline
 
Introduction to SQLAlchemy and Alembic Migrations
Introduction to SQLAlchemy and Alembic MigrationsIntroduction to SQLAlchemy and Alembic Migrations
Introduction to SQLAlchemy and Alembic Migrations
 

Similar to REST API Python Django DRF

Engitec - Minicurso de Django
Engitec - Minicurso de DjangoEngitec - Minicurso de Django
Engitec - Minicurso de DjangoGilson Filho
 
Making web stack tasty using Cloudformation
Making web stack tasty using CloudformationMaking web stack tasty using Cloudformation
Making web stack tasty using CloudformationNicola Salvo
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for BeginnersJason Davies
 
Vue.js + Django - configuración para desarrollo con webpack y HMR
Vue.js + Django - configuración para desarrollo con webpack y HMRVue.js + Django - configuración para desarrollo con webpack y HMR
Vue.js + Django - configuración para desarrollo con webpack y HMRJavier Abadía
 
Django rest framework in 20 minuten
Django rest framework in 20 minutenDjango rest framework in 20 minuten
Django rest framework in 20 minutenAndi Albrecht
 
Django for mobile applications
Django for mobile applicationsDjango for mobile applications
Django for mobile applicationsHassan Abid
 
SCR Annotations for Fun and Profit
SCR Annotations for Fun and ProfitSCR Annotations for Fun and Profit
SCR Annotations for Fun and ProfitMike Pfaff
 
Django framework
Django framework Django framework
Django framework TIB Academy
 
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Easy Step-by-Step Guide to Develop REST APIs with Django REST FrameworkEasy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Easy Step-by-Step Guide to Develop REST APIs with Django REST FrameworkInexture Solutions
 
Django Architecture Introduction
Django Architecture IntroductionDjango Architecture Introduction
Django Architecture IntroductionHaiqi Chen
 
How to Implement Token Authentication Using the Django REST Framework
How to Implement Token Authentication Using the Django REST FrameworkHow to Implement Token Authentication Using the Django REST Framework
How to Implement Token Authentication Using the Django REST FrameworkKaty Slemon
 
Introduction to Django REST Framework, an easy way to build REST framework in...
Introduction to Django REST Framework, an easy way to build REST framework in...Introduction to Django REST Framework, an easy way to build REST framework in...
Introduction to Django REST Framework, an easy way to build REST framework in...Zhe Li
 
Go swagger tutorial how to create golang api documentation using go swagger (1)
Go swagger tutorial how to create golang api documentation using go swagger (1)Go swagger tutorial how to create golang api documentation using go swagger (1)
Go swagger tutorial how to create golang api documentation using go swagger (1)Katy Slemon
 
Mini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico CesMini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico CesLeonardo Fernandes
 
Web Development in Django
Web Development in DjangoWeb Development in Django
Web Development in DjangoLakshman Prasad
 

Similar to REST API Python Django DRF (20)

Django
DjangoDjango
Django
 
Engitec - Minicurso de Django
Engitec - Minicurso de DjangoEngitec - Minicurso de Django
Engitec - Minicurso de Django
 
Making web stack tasty using Cloudformation
Making web stack tasty using CloudformationMaking web stack tasty using Cloudformation
Making web stack tasty using Cloudformation
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for Beginners
 
Gohan
GohanGohan
Gohan
 
Vue.js + Django - configuración para desarrollo con webpack y HMR
Vue.js + Django - configuración para desarrollo con webpack y HMRVue.js + Django - configuración para desarrollo con webpack y HMR
Vue.js + Django - configuración para desarrollo con webpack y HMR
 
DJango
DJangoDJango
DJango
 
Django rest framework in 20 minuten
Django rest framework in 20 minutenDjango rest framework in 20 minuten
Django rest framework in 20 minuten
 
Django for mobile applications
Django for mobile applicationsDjango for mobile applications
Django for mobile applications
 
SCR Annotations for Fun and Profit
SCR Annotations for Fun and ProfitSCR Annotations for Fun and Profit
SCR Annotations for Fun and Profit
 
Django web framework
Django web frameworkDjango web framework
Django web framework
 
Django framework
Django framework Django framework
Django framework
 
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Easy Step-by-Step Guide to Develop REST APIs with Django REST FrameworkEasy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
 
Django Architecture Introduction
Django Architecture IntroductionDjango Architecture Introduction
Django Architecture Introduction
 
How to Implement Token Authentication Using the Django REST Framework
How to Implement Token Authentication Using the Django REST FrameworkHow to Implement Token Authentication Using the Django REST Framework
How to Implement Token Authentication Using the Django REST Framework
 
Django
DjangoDjango
Django
 
Introduction to Django REST Framework, an easy way to build REST framework in...
Introduction to Django REST Framework, an easy way to build REST framework in...Introduction to Django REST Framework, an easy way to build REST framework in...
Introduction to Django REST Framework, an easy way to build REST framework in...
 
Go swagger tutorial how to create golang api documentation using go swagger (1)
Go swagger tutorial how to create golang api documentation using go swagger (1)Go swagger tutorial how to create golang api documentation using go swagger (1)
Go swagger tutorial how to create golang api documentation using go swagger (1)
 
Mini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico CesMini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico Ces
 
Web Development in Django
Web Development in DjangoWeb Development in Django
Web Development in Django
 

Recently uploaded

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 

Recently uploaded (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 

REST API Python Django DRF

  • 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?
  • 14.
  • 15.
  • 16.
  • 18.
  • 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: santosh@phunka.com Thanks !