SlideShare une entreprise Scribd logo
1  sur  29
Télécharger pour lire hors ligne
KISS REST API
 @yurevich, oDesk corp.
     ekb.py 2012




                          1
Plan

• K.O.
• Good practices
• Real world sample
• Toolset

                       2
Good API
• Easy
 • to use
 • to read
 • to extend
• Complete
• Consistent
                     3
REST
• stateless (no cookies & sessions)
• resources identification (URLs)
• representation (JSON, XML,YaML)
• manipulation of resources through
  representation
• self-descriptive messages
• hypermedia (Links)
                                      4
Good samples

• Twitter API
• Twilio API
• Amazon S3 API


                     5
Good practices

• Though not so universal
• http://blog.feedly.com/2009/05/06/best-
  practices-for-building-json-rest-web-
  services/
• http://jacobian.org/writing/rest-worst-
  practices/


                                            6
Writing spec
    Document it first
• Real use-cases
• Complete and closed set
• Future kills now
• Explicit versioning

                            7
Beginners mistakes
• Resource = model
 • Think about married couple
• All methods should be implemented for
  every resource
 • Update user account activation? Delete
    sent SMS message?
• Custom methods
                                            8
Use nouns
  (learn passive voice)
• User sends SMS message =>
  A SMS message is created
• Article is reviewed by editor =>
  Review of article is created
• The user deactivates account =>
  User account activation is deleted



                                       9
Namespaces


• https://smsgate/v2/messages
  (or https://smsgate/20120210/messages) VS
  https://smsgate/messages




                                              10
Resources


• Resources are NOUNs
• https://smsgate/v2/messages VS
  https://smsgate/v2/send-message




                                    11
URLs


• Required GET params must be part of URL
 • http://smsgate/v2/messages/{id} instead of
    http://smsgate/v2/message?id={id}




                                                12
Auth! SSL!

• https://smsgate/v2/messages VS
  http://smsgate/v2/messages
• Poor man auth: token-based
• Production ready: oAuth2


                                   13
Real world sample 0

• SMS Gate
 • GET http://smsgate/sendMessage?
    number=780020000000&text=Send+it
    +please




                                       14
Real world sample
• SMS Gate
 • Resource: Text Message /message:
    • Create new one (send) —
        POST /messages
     • Get information about status
        GET /messages/{id}
 • version: 2
                                      15
Real world sample 2
• POST https://smsgate2/v2/messages
  > message=Send%20it
  %20please&target=780020000000
• 201 Created
  Location: https://smsgate2/v2/messages/242
  {‘target’: ‘78002000000’, ‘url’: ‘https://
  smsgate2/v2/message’, ‘status’: ‘queued’}


                                               16
Toolset

• Documentation
• Backend
• Validation
• JSON generation
• What’s next?

                       17
Toolset: documentation
• Sphinx (ReST)
 • HTTP Domain — https://github.com/
    deceze/Sphinx-HTTP-domain
 • httpdomain — https://bitbucket.org/
    birkenfeld/sphinx-contrib
• Markdown
 • https://github.com/coopernurse/doctorj
                                            18
Toolset: prototyping

• Red barrel
 • External DSL (hello, PHP&Ruby)
 • Self-documented
 • Easy to distribute
 • Only for prototyping

                                    19
Flask
• Simple
• You get what you need
• A lot of bootstrapping code
 • Attention to details
 • Chance to get hardcoded result
• In our projects most load-intensive APIs are
  implemented using Flask
                                                 20
Django+Piston

• Good set of features (for that time)
• Built-in formatters
 • works well, on Accept header
• Methods are strictly mapped to actions
• Hard to reuse different forms in single
  handler
• It’s obsolete
                                            21
Django+TastyPie

• A lot of features
• Pure Resource, ModelResource
• Pagination
• In our team richest APIs are implemented
  in TastyPie



                                             22
Toolset:Validation

• http://bitbucket.org/jek/flatland/
 • Looks cool
 • Not so obvious for nested structures
 • Internals — OMG

                                          23
Toolset:Validation

• https://github.com/Deepwalker/procrustes
 • Data and forms validation
 • Simple
 • Good as prototype, not so good for
    production
 • lack of documentation
                                             24
Toolset:Validation
• https://github.com/Deepwalker/trafaret
 • Very nice syntax
 • Easy but supports complex nested
    structures
 • Lack of documentation
 • No forms validation
                                           25
Toolset: JSON writer

• /dev/hands
• Ruby:
 • https://github.com/inem/tequila
 • https://github.com/nesquena/rabl

                                      26
What’s next?
• JSON Schema
 • Validation
 • Discovery
• http://json-schema.org/
• http://nico.vahlas.eu/2010/04/23/json-
  schema-specifying-and-validating-json-data-
  structures/
• http://shane.caraveo.com/2011/06/30/using-
  json-schema-for-exploring-api-servers/
                                                27
Surprise

• Dzen Python works for REST APIs
•curl http://pure-
  dawn-9186.herokuapp.com/
  import-this




                                    28
Thanks

• Questions?
• yyurevich@jellycrystal.com
• follow me on twitter @yurevich


                                   29

Contenu connexe

Tendances

Tendances (13)

Rack
RackRack
Rack
 
Redis At 6Wunderkinder
Redis At 6WunderkinderRedis At 6Wunderkinder
Redis At 6Wunderkinder
 
Elastic search intro-@lamper
Elastic search intro-@lamperElastic search intro-@lamper
Elastic search intro-@lamper
 
PLAT-16 Using Enterprise Content in Grails
PLAT-16 Using Enterprise Content in GrailsPLAT-16 Using Enterprise Content in Grails
PLAT-16 Using Enterprise Content in Grails
 
Florian Koch - Monitoring CoreOS with Zabbix
Florian Koch - Monitoring CoreOS with ZabbixFlorian Koch - Monitoring CoreOS with Zabbix
Florian Koch - Monitoring CoreOS with Zabbix
 
Webinar: Developing with the modern App Stack: MEAN and MERN (with Angular2 a...
Webinar: Developing with the modern App Stack: MEAN and MERN (with Angular2 a...Webinar: Developing with the modern App Stack: MEAN and MERN (with Angular2 a...
Webinar: Developing with the modern App Stack: MEAN and MERN (with Angular2 a...
 
2016-05-12 DCRUG React.rb
2016-05-12 DCRUG React.rb2016-05-12 DCRUG React.rb
2016-05-12 DCRUG React.rb
 
RESTFul development with Apache sling
RESTFul development with Apache slingRESTFul development with Apache sling
RESTFul development with Apache sling
 
Polyglot Messaging with Apache ActiveMQ
Polyglot Messaging with Apache ActiveMQPolyglot Messaging with Apache ActiveMQ
Polyglot Messaging with Apache ActiveMQ
 
Mongo Web Apps: OSCON 2011
Mongo Web Apps: OSCON 2011Mongo Web Apps: OSCON 2011
Mongo Web Apps: OSCON 2011
 
Scala with mongodb
Scala with mongodbScala with mongodb
Scala with mongodb
 
Connecting to Web Services on Android
Connecting to Web Services on AndroidConnecting to Web Services on Android
Connecting to Web Services on Android
 
Eclipse Dirigible WebIDE - Deep Dive
Eclipse Dirigible WebIDE - Deep DiveEclipse Dirigible WebIDE - Deep Dive
Eclipse Dirigible WebIDE - Deep Dive
 

Similaire à ekbpy'2012- Юрий Юревич - Как сделать REST API на Python

Progressive Enhancement using WSGI
Progressive Enhancement using WSGIProgressive Enhancement using WSGI
Progressive Enhancement using WSGI
Matthew Wilkes
 
MEAN Stack WeNode Barcelona Workshop
MEAN Stack WeNode Barcelona WorkshopMEAN Stack WeNode Barcelona Workshop
MEAN Stack WeNode Barcelona Workshop
Valeri Karpov
 

Similaire à ekbpy'2012- Юрий Юревич - Как сделать REST API на Python (20)

RESTful web
RESTful webRESTful web
RESTful web
 
Middleware in Golang: InVision's Rye
Middleware in Golang: InVision's RyeMiddleware in Golang: InVision's Rye
Middleware in Golang: InVision's Rye
 
Service stack all the things
Service stack all the thingsService stack all the things
Service stack all the things
 
Progressive Enhancement using WSGI
Progressive Enhancement using WSGIProgressive Enhancement using WSGI
Progressive Enhancement using WSGI
 
MEAN Stack WeNode Barcelona Workshop
MEAN Stack WeNode Barcelona WorkshopMEAN Stack WeNode Barcelona Workshop
MEAN Stack WeNode Barcelona Workshop
 
Scaling with swagger
Scaling with swaggerScaling with swagger
Scaling with swagger
 
API Design & Security in django
API Design & Security in djangoAPI Design & Security in django
API Design & Security in django
 
How to Contribute to Apache Usergrid
How to Contribute to Apache UsergridHow to Contribute to Apache Usergrid
How to Contribute to Apache Usergrid
 
Intro to CakePHP
Intro to CakePHPIntro to CakePHP
Intro to CakePHP
 
CouchDB for Web Applications - Erlang Factory London 2009
CouchDB for Web Applications - Erlang Factory London 2009CouchDB for Web Applications - Erlang Factory London 2009
CouchDB for Web Applications - Erlang Factory London 2009
 
Node.js
Node.jsNode.js
Node.js
 
Digging deeper into service stack
Digging deeper into service stackDigging deeper into service stack
Digging deeper into service stack
 
Maine WordPress Meetup JSON REST API, 3/16/2016
Maine WordPress Meetup JSON REST API, 3/16/2016Maine WordPress Meetup JSON REST API, 3/16/2016
Maine WordPress Meetup JSON REST API, 3/16/2016
 
Ship It ! with Ruby/ Rails Ecosystem
Ship It ! with Ruby/ Rails EcosystemShip It ! with Ruby/ Rails Ecosystem
Ship It ! with Ruby/ Rails Ecosystem
 
Be faster then rabbits
Be faster then rabbitsBe faster then rabbits
Be faster then rabbits
 
Rapid development with Rails
Rapid development with RailsRapid development with Rails
Rapid development with Rails
 
Code for Startup MVP (Ruby on Rails) Session 1
Code for Startup MVP (Ruby on Rails) Session 1Code for Startup MVP (Ruby on Rails) Session 1
Code for Startup MVP (Ruby on Rails) Session 1
 
Streams API (Web Engines Hackfest 2015)
Streams API (Web Engines Hackfest 2015)Streams API (Web Engines Hackfest 2015)
Streams API (Web Engines Hackfest 2015)
 
How to audit Drupal Sites for performance, content and best practices
How to audit Drupal Sites for performance, content and best practicesHow to audit Drupal Sites for performance, content and best practices
How to audit Drupal Sites for performance, content and best practices
 
Hacking Adobe Experience Manager sites
Hacking Adobe Experience Manager sitesHacking Adobe Experience Manager sites
Hacking Adobe Experience Manager sites
 

Plus de it-people

«Про аналитику и серебряные пули» Александр Подсобляев, Rambler&Co
«Про аналитику и серебряные пули» Александр Подсобляев, Rambler&Co«Про аналитику и серебряные пули» Александр Подсобляев, Rambler&Co
«Про аналитику и серебряные пули» Александр Подсобляев, Rambler&Co
it-people
 
«Отладка в Python 3.6: Быстрее, Выше, Сильнее» Елизавета Шашкова, JetBrains
«Отладка в Python 3.6: Быстрее, Выше, Сильнее» Елизавета Шашкова, JetBrains«Отладка в Python 3.6: Быстрее, Выше, Сильнее» Елизавета Шашкова, JetBrains
«Отладка в Python 3.6: Быстрее, Выше, Сильнее» Елизавета Шашкова, JetBrains
it-people
 
«How I Learned to Stop Worrying and Love the BFG: нагрузочное тестирование со...
«How I Learned to Stop Worrying and Love the BFG: нагрузочное тестирование со...«How I Learned to Stop Worrying and Love the BFG: нагрузочное тестирование со...
«How I Learned to Stop Worrying and Love the BFG: нагрузочное тестирование со...
it-people
 
«Write once run anywhere — почём опиум для народа?» Игорь Новиков, Scalr
«Write once run anywhere — почём опиум для народа?» Игорь Новиков, Scalr«Write once run anywhere — почём опиум для народа?» Игорь Новиков, Scalr
«Write once run anywhere — почём опиум для народа?» Игорь Новиков, Scalr
it-people
 
«Gensim — тематическое моделирование для людей» Иван Меньших, Лев Константино...
«Gensim — тематическое моделирование для людей» Иван Меньших, Лев Константино...«Gensim — тематическое моделирование для людей» Иван Меньших, Лев Константино...
«Gensim — тематическое моделирование для людей» Иван Меньших, Лев Константино...
it-people
 
«Тотальный контроль производительности» Михаил Юматов, ЦИАН
«Тотальный контроль производительности» Михаил Юматов, ЦИАН«Тотальный контроль производительности» Михаил Юматов, ЦИАН
«Тотальный контроль производительности» Михаил Юматов, ЦИАН
it-people
 
«Детские болезни live-чата» Ольга Сентемова, Тинькофф Банк
«Детские болезни live-чата» Ольга Сентемова, Тинькофф Банк«Детские болезни live-чата» Ольга Сентемова, Тинькофф Банк
«Детские болезни live-чата» Ольга Сентемова, Тинькофф Банк
it-people
 
«Микросервисы наносят ответный удар!» Олег Чуркин, Rambler&Co
«Микросервисы наносят ответный удар!» Олег Чуркин, Rambler&Co«Микросервисы наносят ответный удар!» Олег Чуркин, Rambler&Co
«Микросервисы наносят ответный удар!» Олег Чуркин, Rambler&Co
it-people
 
«Память и Python. Что надо знать для счастья?» Алексей Кузьмин, ЦНС
«Память и Python. Что надо знать для счастья?» Алексей Кузьмин, ЦНС«Память и Python. Что надо знать для счастья?» Алексей Кузьмин, ЦНС
«Память и Python. Что надо знать для счастья?» Алексей Кузьмин, ЦНС
it-people
 
«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...
«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...
«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...
it-people
 
«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies
«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies
«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies
it-people
 
«Как сделать так, чтобы тесты на Swift не причиняли боль» Сычев Александр, Ra...
«Как сделать так, чтобы тесты на Swift не причиняли боль» Сычев Александр, Ra...«Как сделать так, чтобы тесты на Swift не причиняли боль» Сычев Александр, Ra...
«Как сделать так, чтобы тесты на Swift не причиняли боль» Сычев Александр, Ra...
it-people
 
«Кошелек или деньги: сложный выбор между памятью и процессором» Алексеенко Иг...
«Кошелек или деньги: сложный выбор между памятью и процессором» Алексеенко Иг...«Кошелек или деньги: сложный выбор между памятью и процессором» Алексеенко Иг...
«Кошелек или деньги: сложный выбор между памятью и процессором» Алексеенко Иг...
it-people
 

Plus de it-people (20)

«Про аналитику и серебряные пули» Александр Подсобляев, Rambler&Co
«Про аналитику и серебряные пули» Александр Подсобляев, Rambler&Co«Про аналитику и серебряные пули» Александр Подсобляев, Rambler&Co
«Про аналитику и серебряные пули» Александр Подсобляев, Rambler&Co
 
«Scrapy internals» Александр Сибиряков, Scrapinghub
«Scrapy internals» Александр Сибиряков, Scrapinghub«Scrapy internals» Александр Сибиряков, Scrapinghub
«Scrapy internals» Александр Сибиряков, Scrapinghub
 
«Отладка в Python 3.6: Быстрее, Выше, Сильнее» Елизавета Шашкова, JetBrains
«Отладка в Python 3.6: Быстрее, Выше, Сильнее» Елизавета Шашкова, JetBrains«Отладка в Python 3.6: Быстрее, Выше, Сильнее» Елизавета Шашкова, JetBrains
«Отладка в Python 3.6: Быстрее, Выше, Сильнее» Елизавета Шашкова, JetBrains
 
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
 
«Ещё один Поиск Яндекса» Александр Кошелев, Яндекс
«Ещё один Поиск Яндекса» Александр Кошелев, Яндекс«Ещё один Поиск Яндекса» Александр Кошелев, Яндекс
«Ещё один Поиск Яндекса» Александр Кошелев, Яндекс
 
«How I Learned to Stop Worrying and Love the BFG: нагрузочное тестирование со...
«How I Learned to Stop Worrying and Love the BFG: нагрузочное тестирование со...«How I Learned to Stop Worrying and Love the BFG: нагрузочное тестирование со...
«How I Learned to Stop Worrying and Love the BFG: нагрузочное тестирование со...
 
«Write once run anywhere — почём опиум для народа?» Игорь Новиков, Scalr
«Write once run anywhere — почём опиум для народа?» Игорь Новиков, Scalr«Write once run anywhere — почём опиум для народа?» Игорь Новиков, Scalr
«Write once run anywhere — почём опиум для народа?» Игорь Новиков, Scalr
 
«Gensim — тематическое моделирование для людей» Иван Меньших, Лев Константино...
«Gensim — тематическое моделирование для людей» Иван Меньших, Лев Константино...«Gensim — тематическое моделирование для людей» Иван Меньших, Лев Константино...
«Gensim — тематическое моделирование для людей» Иван Меньших, Лев Константино...
 
«Тотальный контроль производительности» Михаил Юматов, ЦИАН
«Тотальный контроль производительности» Михаил Юматов, ЦИАН«Тотальный контроль производительности» Михаил Юматов, ЦИАН
«Тотальный контроль производительности» Михаил Юматов, ЦИАН
 
«Детские болезни live-чата» Ольга Сентемова, Тинькофф Банк
«Детские болезни live-чата» Ольга Сентемова, Тинькофф Банк«Детские болезни live-чата» Ольга Сентемова, Тинькофф Банк
«Детские болезни live-чата» Ольга Сентемова, Тинькофф Банк
 
«Микросервисы наносят ответный удар!» Олег Чуркин, Rambler&Co
«Микросервисы наносят ответный удар!» Олег Чуркин, Rambler&Co«Микросервисы наносят ответный удар!» Олег Чуркин, Rambler&Co
«Микросервисы наносят ответный удар!» Олег Чуркин, Rambler&Co
 
«Память и Python. Что надо знать для счастья?» Алексей Кузьмин, ЦНС
«Память и Python. Что надо знать для счастья?» Алексей Кузьмин, ЦНС«Память и Python. Что надо знать для счастья?» Алексей Кузьмин, ЦНС
«Память и Python. Что надо знать для счастья?» Алексей Кузьмин, ЦНС
 
«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...
«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...
«Что такое serverless-архитектура и как с ней жить?» Николай Марков, Aligned ...
 
«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies
«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies
«Python на острие бритвы: PyPy project» Александр Кошкин, Positive Technologies
 
«PyWat. А хорошо ли вы знаете Python?» Александр Швец, Marilyn System
«PyWat. А хорошо ли вы знаете Python?» Александр Швец, Marilyn System«PyWat. А хорошо ли вы знаете Python?» Александр Швец, Marilyn System
«PyWat. А хорошо ли вы знаете Python?» Александр Швец, Marilyn System
 
«(Без)опасный Python», Иван Цыганов, Positive Technologies
«(Без)опасный Python», Иван Цыганов, Positive Technologies«(Без)опасный Python», Иван Цыганов, Positive Technologies
«(Без)опасный Python», Иван Цыганов, Positive Technologies
 
«Python of Things», Кирилл Борисов, Яндекс
«Python of Things», Кирилл Борисов, Яндекс«Python of Things», Кирилл Борисов, Яндекс
«Python of Things», Кирилл Борисов, Яндекс
 
«Как сделать так, чтобы тесты на Swift не причиняли боль» Сычев Александр, Ra...
«Как сделать так, чтобы тесты на Swift не причиняли боль» Сычев Александр, Ra...«Как сделать так, чтобы тесты на Swift не причиняли боль» Сычев Александр, Ra...
«Как сделать так, чтобы тесты на Swift не причиняли боль» Сычев Александр, Ra...
 
«Клиенту и серверу нужно поговорить» Прокопов Никита, Cognician
«Клиенту и серверу нужно поговорить» Прокопов Никита, Cognician«Клиенту и серверу нужно поговорить» Прокопов Никита, Cognician
«Клиенту и серверу нужно поговорить» Прокопов Никита, Cognician
 
«Кошелек или деньги: сложный выбор между памятью и процессором» Алексеенко Иг...
«Кошелек или деньги: сложный выбор между памятью и процессором» Алексеенко Иг...«Кошелек или деньги: сложный выбор между памятью и процессором» Алексеенко Иг...
«Кошелек или деньги: сложный выбор между памятью и процессором» Алексеенко Иг...
 

Dernier

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Dernier (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave 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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

ekbpy'2012- Юрий Юревич - Как сделать REST API на Python

  • 1. KISS REST API @yurevich, oDesk corp. ekb.py 2012 1
  • 2. Plan • K.O. • Good practices • Real world sample • Toolset 2
  • 3. Good API • Easy • to use • to read • to extend • Complete • Consistent 3
  • 4. REST • stateless (no cookies & sessions) • resources identification (URLs) • representation (JSON, XML,YaML) • manipulation of resources through representation • self-descriptive messages • hypermedia (Links) 4
  • 5. Good samples • Twitter API • Twilio API • Amazon S3 API 5
  • 6. Good practices • Though not so universal • http://blog.feedly.com/2009/05/06/best- practices-for-building-json-rest-web- services/ • http://jacobian.org/writing/rest-worst- practices/ 6
  • 7. Writing spec Document it first • Real use-cases • Complete and closed set • Future kills now • Explicit versioning 7
  • 8. Beginners mistakes • Resource = model • Think about married couple • All methods should be implemented for every resource • Update user account activation? Delete sent SMS message? • Custom methods 8
  • 9. Use nouns (learn passive voice) • User sends SMS message => A SMS message is created • Article is reviewed by editor => Review of article is created • The user deactivates account => User account activation is deleted 9
  • 10. Namespaces • https://smsgate/v2/messages (or https://smsgate/20120210/messages) VS https://smsgate/messages 10
  • 11. Resources • Resources are NOUNs • https://smsgate/v2/messages VS https://smsgate/v2/send-message 11
  • 12. URLs • Required GET params must be part of URL • http://smsgate/v2/messages/{id} instead of http://smsgate/v2/message?id={id} 12
  • 13. Auth! SSL! • https://smsgate/v2/messages VS http://smsgate/v2/messages • Poor man auth: token-based • Production ready: oAuth2 13
  • 14. Real world sample 0 • SMS Gate • GET http://smsgate/sendMessage? number=780020000000&text=Send+it +please 14
  • 15. Real world sample • SMS Gate • Resource: Text Message /message: • Create new one (send) — POST /messages • Get information about status GET /messages/{id} • version: 2 15
  • 16. Real world sample 2 • POST https://smsgate2/v2/messages > message=Send%20it %20please&target=780020000000 • 201 Created Location: https://smsgate2/v2/messages/242 {‘target’: ‘78002000000’, ‘url’: ‘https:// smsgate2/v2/message’, ‘status’: ‘queued’} 16
  • 17. Toolset • Documentation • Backend • Validation • JSON generation • What’s next? 17
  • 18. Toolset: documentation • Sphinx (ReST) • HTTP Domain — https://github.com/ deceze/Sphinx-HTTP-domain • httpdomain — https://bitbucket.org/ birkenfeld/sphinx-contrib • Markdown • https://github.com/coopernurse/doctorj 18
  • 19. Toolset: prototyping • Red barrel • External DSL (hello, PHP&Ruby) • Self-documented • Easy to distribute • Only for prototyping 19
  • 20. Flask • Simple • You get what you need • A lot of bootstrapping code • Attention to details • Chance to get hardcoded result • In our projects most load-intensive APIs are implemented using Flask 20
  • 21. Django+Piston • Good set of features (for that time) • Built-in formatters • works well, on Accept header • Methods are strictly mapped to actions • Hard to reuse different forms in single handler • It’s obsolete 21
  • 22. Django+TastyPie • A lot of features • Pure Resource, ModelResource • Pagination • In our team richest APIs are implemented in TastyPie 22
  • 23. Toolset:Validation • http://bitbucket.org/jek/flatland/ • Looks cool • Not so obvious for nested structures • Internals — OMG 23
  • 24. Toolset:Validation • https://github.com/Deepwalker/procrustes • Data and forms validation • Simple • Good as prototype, not so good for production • lack of documentation 24
  • 25. Toolset:Validation • https://github.com/Deepwalker/trafaret • Very nice syntax • Easy but supports complex nested structures • Lack of documentation • No forms validation 25
  • 26. Toolset: JSON writer • /dev/hands • Ruby: • https://github.com/inem/tequila • https://github.com/nesquena/rabl 26
  • 27. What’s next? • JSON Schema • Validation • Discovery • http://json-schema.org/ • http://nico.vahlas.eu/2010/04/23/json- schema-specifying-and-validating-json-data- structures/ • http://shane.caraveo.com/2011/06/30/using- json-schema-for-exploring-api-servers/ 27
  • 28. Surprise • Dzen Python works for REST APIs •curl http://pure- dawn-9186.herokuapp.com/ import-this 28
  • 29. Thanks • Questions? • yyurevich@jellycrystal.com • follow me on twitter @yurevich 29