SlideShare une entreprise Scribd logo
1  sur  20
Télécharger pour lire hors ligne
REST APIs for Cruel
World
(using Python)
April 12, 2004
What is REST?
• Client-Server
• Stateless
• Cacheable
• Layered System
• Uniform Interface
• Code on demand (optional)
Why REST
• REST is awesome
• SOAP is ugly
• all others are even uglier
REST ==* JSON
* at least let’s wish this
REST verbs
HTTP Method Action Examples
GET
Obtain information
about a resource
http://example.com/api/orders/
(retrieve list of orders)
GET
Obtain information
about a resource
http://example.com/api/orders/123
(retrieve order #123)
POST
Create a new
resource
http://example.com/api/orders
(create a new order, from data
provided with the request)
PUT Update a resource
http://example.com/api/orders/123
(update order #123, from data
provided with the request)
DELETE Delete a resource http://example.com/api/orders/123
(delete order #123)
API versions
• Always use version
• Versions in URLs:
• /api/v1.0
• /api/20140412/
• Versions in headers
Authentication
• End-client to API server (oAuth)
• Server-to-Server
Server-to-Server
• API key identification
• Signing with API secret
• Timestamp (servers should be ntp synced)
• Whitelists (optional)
import hashlib!
import hmac!
!
def get_signature(data, secret_key):!
if isinstance(data, dict):!
data = u'&'.join(!
(u'='.join((key, value))!
for (key, value) in sorted(data.iteritems())))!
hash_key = hmac.new(!
! ! secret_key, !
! ! data.encode('utf-8'), !
! ! hashlib.sha256)!
return hash_key.hexdigest()
timestamp = get_utc_timestamp()!
!
data = 'api_key=test&key=test&timestamp=%s' % timestamp!
!
signature = get_signature(data, TEST_SECRET_KEY)!
!
resp = (!
! self.client.get(“/test?%s&signature=%s" % (!
! ! data, signature))!
)
REST and Django
• Django-tastypie
• Django-rest-framework
Django-tastypie
• Django model is resource
• All actions are hardly linked with
models
• http://tastypieapi.org/
Django-rest-framework
• The Web browseable API
• Authentication policies including OAuth1a and
OAuth2 out of the box.
• Serialization that supports both ORM and non-ORM
data sources.
• Customizable all the way down
• http://www.django-rest-framework.org/
from rest_framework.views import APIView!
from rest_framework.response import Response!
from rest_framework import (!
! authentication, permissions!
)!
!
class ListUsers(APIView):!
!
authentication_classes = (!
! ! authentication.TokenAuthentication,)!
permission_classes = (permissions.IsAdminUser,)!
!
def get(self, request, format=None):!
usernames = [!
! ! ! user.username for user in User.objects.all()]!
return Response(usernames)
django-rest-swagger
!
!
!
!
• https://github.com/marcgibbons/django-rest-
swagger
Flask-RESTful
• http://flask-restful.readthedocs.org/en/latest/
from flask import Flask!
from flask.ext.restful import Api, Resource!
!
app = Flask(__name__)!
api = Api(app)!
!
class UserAPI(Resource):!
def get(self, id):!
pass!
!
def put(self, id):!
pass!
!
def delete(self, id):!
pass!
!
api.add_resource(UserAPI, '/users/<int:id>', endpoint = 'user')
API testing
class ApiAuthTestCase(BaseApiTestCase):!
def test_get_without_params(self):!
resp = self.client.get('/test')!
self.assertEquals(resp.status_code, 400)!
!
def test_post_without_params(self):!
resp = self.client.post('/test')!
self.assertEquals(resp.status_code, 400)!
!
def test_get_bad_signature(self):!
timestamp = get_utc_timestamp()!
resp = self.client.get(!
'/test?key=test&api_key=test&signature=bad&timestamp=%s' %!
timestamp)!
self.assertEquals(resp.status_code, 403)!
Volodymyr Hotsyk
https://github.com/hotsyk/
@hotsyk
Questions?

Contenu connexe

Tendances

PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2
Graham Dumpleton
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparison
Hiroshi Nakamura
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
it-people
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
Praveen Gollakota
 

Tendances (20)

Building an API with Django and Django REST Framework
Building an API with Django and Django REST FrameworkBuilding an API with Django and Django REST Framework
Building an API with Django and Django REST Framework
 
Flask Introduction - Python Meetup
Flask Introduction - Python MeetupFlask Introduction - Python Meetup
Flask Introduction - Python Meetup
 
Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18
 
PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparison
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
 
Web develop in flask
Web develop in flaskWeb develop in flask
Web develop in flask
 
Retrofit Android by Chris Ollenburg
Retrofit Android by Chris OllenburgRetrofit Android by Chris Ollenburg
Retrofit Android by Chris Ollenburg
 
Webscraping with asyncio
Webscraping with asyncioWebscraping with asyncio
Webscraping with asyncio
 
Rest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemyRest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemy
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in details
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
 
Learn flask in 90mins
Learn flask in 90minsLearn flask in 90mins
Learn flask in 90mins
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
XamarinとAWSをつないでみた話
XamarinとAWSをつないでみた話XamarinとAWSをつないでみた話
XamarinとAWSをつないでみた話
 
RESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher PecoraroRESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher Pecoraro
 
RESTful API 제대로 만들기
RESTful API 제대로 만들기RESTful API 제대로 만들기
RESTful API 제대로 만들기
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
 
Real time server
Real time serverReal time server
Real time server
 
8 Minutes On Rack
8 Minutes On Rack8 Minutes On Rack
8 Minutes On Rack
 

En vedette

En vedette (20)

Building Automated REST APIs with Python
Building Automated REST APIs with PythonBuilding Automated REST APIs with Python
Building Automated REST APIs with Python
 
The Basic Introduction of Open vSwitch
The Basic Introduction of Open vSwitchThe Basic Introduction of Open vSwitch
The Basic Introduction of Open vSwitch
 
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
 
JSON and REST
JSON and RESTJSON and REST
JSON and REST
 
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
 
Writing Idiomatic Python: PyCon PH 2017 Keynote
Writing Idiomatic Python: PyCon PH 2017 KeynoteWriting Idiomatic Python: PyCon PH 2017 Keynote
Writing Idiomatic Python: PyCon PH 2017 Keynote
 
Building a Dynamic Website Using Django
Building a Dynamic Website Using DjangoBuilding a Dynamic Website Using Django
Building a Dynamic Website Using Django
 
Atlanta OpenStack 2014 Chef for OpenStack Deployment Workshop
Atlanta OpenStack 2014 Chef for OpenStack Deployment WorkshopAtlanta OpenStack 2014 Chef for OpenStack Deployment Workshop
Atlanta OpenStack 2014 Chef for OpenStack Deployment Workshop
 
Open-E DSS V7 Active-Active Load Balanced iSCSI HA Cluster (with bonding)
Open-E DSS V7 Active-Active Load Balanced iSCSI HA Cluster (with bonding)Open-E DSS V7 Active-Active Load Balanced iSCSI HA Cluster (with bonding)
Open-E DSS V7 Active-Active Load Balanced iSCSI HA Cluster (with bonding)
 
Pycon 2008: Python Command-line Tools *Nix
Pycon 2008:  Python Command-line Tools *NixPycon 2008:  Python Command-line Tools *Nix
Pycon 2008: Python Command-line Tools *Nix
 
Red Hat Storage Day Seattle: Why Software-Defined Storage Matters
Red Hat Storage Day Seattle: Why Software-Defined Storage MattersRed Hat Storage Day Seattle: Why Software-Defined Storage Matters
Red Hat Storage Day Seattle: Why Software-Defined Storage Matters
 
OpenStack Deployment with Chef Workshop
OpenStack Deployment with Chef WorkshopOpenStack Deployment with Chef Workshop
OpenStack Deployment with Chef Workshop
 
Modern Web App Development using ClojureScript & React.js / Baishampayan “BG”...
Modern Web App Development using ClojureScript & React.js / Baishampayan “BG”...Modern Web App Development using ClojureScript & React.js / Baishampayan “BG”...
Modern Web App Development using ClojureScript & React.js / Baishampayan “BG”...
 
Introduction to Apache Synapse
Introduction to Apache SynapseIntroduction to Apache Synapse
Introduction to Apache Synapse
 
Event Driven Architecture - MeshU - Ilya Grigorik
Event Driven Architecture - MeshU - Ilya GrigorikEvent Driven Architecture - MeshU - Ilya Grigorik
Event Driven Architecture - MeshU - Ilya Grigorik
 
Best Practice for Deploying Application with Heat
Best Practice for Deploying Application with HeatBest Practice for Deploying Application with Heat
Best Practice for Deploying Application with Heat
 
Swift Architecture and Practice, by Alex Yang
Swift Architecture and Practice, by Alex YangSwift Architecture and Practice, by Alex Yang
Swift Architecture and Practice, by Alex Yang
 
TXLF: Automated Deployment of OpenStack with Chef
TXLF: Automated Deployment of OpenStack with ChefTXLF: Automated Deployment of OpenStack with Chef
TXLF: Automated Deployment of OpenStack with Chef
 
Are We Done Yet ? Testing Your OpenStack Deployment
Are We Done Yet ? Testing Your OpenStack DeploymentAre We Done Yet ? Testing Your OpenStack Deployment
Are We Done Yet ? Testing Your OpenStack Deployment
 
React.jsでHowManyPizza
React.jsでHowManyPizzaReact.jsでHowManyPizza
React.jsでHowManyPizza
 

Similaire à Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - 2014.04.12

Rapid API Development ArangoDB Foxx
Rapid API Development ArangoDB FoxxRapid API Development ArangoDB Foxx
Rapid API Development ArangoDB Foxx
Michael Hackstein
 
Python & Django TTT
Python & Django TTTPython & Django TTT
Python & Django TTT
kevinvw
 

Similaire à Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - 2014.04.12 (20)

Intro to CloudStack API
Intro to CloudStack APIIntro to CloudStack API
Intro to CloudStack API
 
Why should I care about REST?
Why should I care about REST?Why should I care about REST?
Why should I care about REST?
 
Rapid API Development ArangoDB Foxx
Rapid API Development ArangoDB FoxxRapid API Development ArangoDB Foxx
Rapid API Development ArangoDB Foxx
 
Api crash
Api crashApi crash
Api crash
 
Api crash
Api crashApi crash
Api crash
 
Api crash
Api crashApi crash
Api crash
 
Api crash
Api crashApi crash
Api crash
 
Api crash
Api crashApi crash
Api crash
 
Api crash
Api crashApi crash
Api crash
 
Api crash
Api crashApi crash
Api crash
 
Python & Django TTT
Python & Django TTTPython & Django TTT
Python & Django TTT
 
Introduction to Monsoon PHP framework
Introduction to Monsoon PHP frameworkIntroduction to Monsoon PHP framework
Introduction to Monsoon PHP framework
 
aip-workshop1-dev-tutorial
aip-workshop1-dev-tutorialaip-workshop1-dev-tutorial
aip-workshop1-dev-tutorial
 
Build A Killer Client For Your REST+JSON API
Build A Killer Client For Your REST+JSON APIBuild A Killer Client For Your REST+JSON API
Build A Killer Client For Your REST+JSON API
 
Exposing Salesforce REST Services Using Swagger
Exposing Salesforce REST Services Using SwaggerExposing Salesforce REST Services Using Swagger
Exposing Salesforce REST Services Using Swagger
 
The never-ending REST API design debate
The never-ending REST API design debateThe never-ending REST API design debate
The never-ending REST API design debate
 
Web Services Testing
Web Services TestingWeb Services Testing
Web Services Testing
 
Resting on your laurels will get you powned
Resting on your laurels will get you pownedResting on your laurels will get you powned
Resting on your laurels will get you powned
 
REST API Security: OAuth 2.0, JWTs, and More!
REST API Security: OAuth 2.0, JWTs, and More!REST API Security: OAuth 2.0, JWTs, and More!
REST API Security: OAuth 2.0, JWTs, and More!
 
Леонід Кузьмін “Сам собі паблішер. Від сайту ігрової студії до універсального...
Леонід Кузьмін “Сам собі паблішер. Від сайту ігрової студії до універсального...Леонід Кузьмін “Сам собі паблішер. Від сайту ігрової студії до універсального...
Леонід Кузьмін “Сам собі паблішер. Від сайту ігрової студії до універсального...
 

Plus de Innovecs

Plus de Innovecs (20)

Building Efficient and High Performing iLottery Solutions
Building Efficient and High Performing iLottery SolutionsBuilding Efficient and High Performing iLottery Solutions
Building Efficient and High Performing iLottery Solutions
 
Innovecs Meetup Lifestory
Innovecs Meetup LifestoryInnovecs Meetup Lifestory
Innovecs Meetup Lifestory
 
Подходы и технологии в React Redux
Подходы и технологии в React ReduxПодходы и технологии в React Redux
Подходы и технологии в React Redux
 
Redux vs RxJS vs Mobx в связке с React
Redux vs RxJS vs Mobx в связке с ReactRedux vs RxJS vs Mobx в связке с React
Redux vs RxJS vs Mobx в связке с React
 
React & Redux (Lazarev)
React & Redux (Lazarev)React & Redux (Lazarev)
React & Redux (Lazarev)
 
Web Platform for Fashion Shop
Web Platform for Fashion ShopWeb Platform for Fashion Shop
Web Platform for Fashion Shop
 
Programmatic Advertising Platform
Programmatic Advertising PlatformProgrammatic Advertising Platform
Programmatic Advertising Platform
 
Multimedia Newsroom
Multimedia NewsroomMultimedia Newsroom
Multimedia Newsroom
 
Media Buying Platform (DSP+DPM)
Media Buying Platform (DSP+DPM)Media Buying Platform (DSP+DPM)
Media Buying Platform (DSP+DPM)
 
Web-based Shipment Application
Web-based Shipment ApplicationWeb-based Shipment Application
Web-based Shipment Application
 
Digital Trading Platform
Digital Trading PlatformDigital Trading Platform
Digital Trading Platform
 
Mobile Insurance Agent
Mobile Insurance AgentMobile Insurance Agent
Mobile Insurance Agent
 
Online Learning Platform
Online Learning PlatformOnline Learning Platform
Online Learning Platform
 
Client Bank
Client BankClient Bank
Client Bank
 
Fertility Tracking App
Fertility Tracking AppFertility Tracking App
Fertility Tracking App
 
Warranty Wallet App
Warranty Wallet AppWarranty Wallet App
Warranty Wallet App
 
Online Bingo Game
Online Bingo GameOnline Bingo Game
Online Bingo Game
 
Secure Messenger
Secure MessengerSecure Messenger
Secure Messenger
 
Search Data Platform
Search Data PlatformSearch Data Platform
Search Data Platform
 
Website Builder for Insurance Agents
Website Builder for Insurance AgentsWebsite Builder for Insurance Agents
Website Builder for Insurance Agents
 

Dernier

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Dernier (20)

Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 

Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - 2014.04.12

  • 1. REST APIs for Cruel World (using Python) April 12, 2004
  • 2.
  • 3. What is REST? • Client-Server • Stateless • Cacheable • Layered System • Uniform Interface • Code on demand (optional)
  • 4. Why REST • REST is awesome • SOAP is ugly • all others are even uglier
  • 5. REST ==* JSON * at least let’s wish this
  • 6. REST verbs HTTP Method Action Examples GET Obtain information about a resource http://example.com/api/orders/ (retrieve list of orders) GET Obtain information about a resource http://example.com/api/orders/123 (retrieve order #123) POST Create a new resource http://example.com/api/orders (create a new order, from data provided with the request) PUT Update a resource http://example.com/api/orders/123 (update order #123, from data provided with the request) DELETE Delete a resource http://example.com/api/orders/123 (delete order #123)
  • 7. API versions • Always use version • Versions in URLs: • /api/v1.0 • /api/20140412/ • Versions in headers
  • 8. Authentication • End-client to API server (oAuth) • Server-to-Server
  • 9. Server-to-Server • API key identification • Signing with API secret • Timestamp (servers should be ntp synced) • Whitelists (optional)
  • 10. import hashlib! import hmac! ! def get_signature(data, secret_key):! if isinstance(data, dict):! data = u'&'.join(! (u'='.join((key, value))! for (key, value) in sorted(data.iteritems())))! hash_key = hmac.new(! ! ! secret_key, ! ! ! data.encode('utf-8'), ! ! ! hashlib.sha256)! return hash_key.hexdigest()
  • 11. timestamp = get_utc_timestamp()! ! data = 'api_key=test&key=test&timestamp=%s' % timestamp! ! signature = get_signature(data, TEST_SECRET_KEY)! ! resp = (! ! self.client.get(“/test?%s&signature=%s" % (! ! ! data, signature))! )
  • 12. REST and Django • Django-tastypie • Django-rest-framework
  • 13. Django-tastypie • Django model is resource • All actions are hardly linked with models • http://tastypieapi.org/
  • 14. Django-rest-framework • The Web browseable API • Authentication policies including OAuth1a and OAuth2 out of the box. • Serialization that supports both ORM and non-ORM data sources. • Customizable all the way down • http://www.django-rest-framework.org/
  • 15. from rest_framework.views import APIView! from rest_framework.response import Response! from rest_framework import (! ! authentication, permissions! )! ! class ListUsers(APIView):! ! authentication_classes = (! ! ! authentication.TokenAuthentication,)! permission_classes = (permissions.IsAdminUser,)! ! def get(self, request, format=None):! usernames = [! ! ! ! user.username for user in User.objects.all()]! return Response(usernames)
  • 18. from flask import Flask! from flask.ext.restful import Api, Resource! ! app = Flask(__name__)! api = Api(app)! ! class UserAPI(Resource):! def get(self, id):! pass! ! def put(self, id):! pass! ! def delete(self, id):! pass! ! api.add_resource(UserAPI, '/users/<int:id>', endpoint = 'user')
  • 19. API testing class ApiAuthTestCase(BaseApiTestCase):! def test_get_without_params(self):! resp = self.client.get('/test')! self.assertEquals(resp.status_code, 400)! ! def test_post_without_params(self):! resp = self.client.post('/test')! self.assertEquals(resp.status_code, 400)! ! def test_get_bad_signature(self):! timestamp = get_utc_timestamp()! resp = self.client.get(! '/test?key=test&api_key=test&signature=bad&timestamp=%s' %! timestamp)! self.assertEquals(resp.status_code, 403)!