SlideShare ist ein Scribd-Unternehmen logo
1 von 29
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Elastic search intro-@lamper
Elastic search intro-@lamperElastic search intro-@lamper
Elastic search intro-@lampermedcl
 
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 GrailsAlfresco Software
 
Florian Koch - Monitoring CoreOS with Zabbix
Florian Koch - Monitoring CoreOS with ZabbixFlorian Koch - Monitoring CoreOS with Zabbix
Florian Koch - Monitoring CoreOS with ZabbixZabbix
 
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...MongoDB
 
2016-05-12 DCRUG React.rb
2016-05-12 DCRUG React.rb2016-05-12 DCRUG React.rb
2016-05-12 DCRUG React.rbawwaiid
 
RESTFul development with Apache sling
RESTFul development with Apache slingRESTFul development with Apache sling
RESTFul development with Apache slingSergii Fesenko
 
Polyglot Messaging with Apache ActiveMQ
Polyglot Messaging with Apache ActiveMQPolyglot Messaging with Apache ActiveMQ
Polyglot Messaging with Apache ActiveMQChristian Posta
 
Mongo Web Apps: OSCON 2011
Mongo Web Apps: OSCON 2011Mongo Web Apps: OSCON 2011
Mongo Web Apps: OSCON 2011rogerbodamer
 
Scala with mongodb
Scala with mongodbScala with mongodb
Scala with mongodbKnoldus Inc.
 
Connecting to Web Services on Android
Connecting to Web Services on AndroidConnecting to Web Services on Android
Connecting to Web Services on Androidsullis
 
Eclipse Dirigible WebIDE - Deep Dive
Eclipse Dirigible WebIDE - Deep DiveEclipse Dirigible WebIDE - Deep Dive
Eclipse Dirigible WebIDE - Deep DiveNedelcho Delchev
 

Was ist angesagt? (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
 

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

RESTful web
RESTful webRESTful web
RESTful webAlvin Qi
 
Middleware in Golang: InVision's Rye
Middleware in Golang: InVision's RyeMiddleware in Golang: InVision's Rye
Middleware in Golang: InVision's RyeCale Hoopes
 
Service stack all the things
Service stack all the thingsService stack all the things
Service stack all the thingscyberzeddk
 
Progressive Enhancement using WSGI
Progressive Enhancement using WSGIProgressive Enhancement using WSGI
Progressive Enhancement using WSGIMatthew Wilkes
 
MEAN Stack WeNode Barcelona Workshop
MEAN Stack WeNode Barcelona WorkshopMEAN Stack WeNode Barcelona Workshop
MEAN Stack WeNode Barcelona WorkshopValeri Karpov
 
Scaling with swagger
Scaling with swaggerScaling with swagger
Scaling with swaggerTony Tam
 
API Design & Security in django
API Design & Security in djangoAPI Design & Security in django
API Design & Security in djangoTareque Hossain
 
How to Contribute to Apache Usergrid
How to Contribute to Apache UsergridHow to Contribute to Apache Usergrid
How to Contribute to Apache UsergridDavid M. Johnson
 
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 2009Jason Davies
 
Digging deeper into service stack
Digging deeper into service stackDigging deeper into service stack
Digging deeper into service stackcyberzeddk
 
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/2016Andre Gagnon
 
Ship It ! with Ruby/ Rails Ecosystem
Ship It ! with Ruby/ Rails EcosystemShip It ! with Ruby/ Rails Ecosystem
Ship It ! with Ruby/ Rails EcosystemYi-Ting Cheng
 
Rapid development with Rails
Rapid development with RailsRapid development with Rails
Rapid development with RailsYi-Ting Cheng
 
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 1Henry S
 
Streams API (Web Engines Hackfest 2015)
Streams API (Web Engines Hackfest 2015)Streams API (Web Engines Hackfest 2015)
Streams API (Web Engines Hackfest 2015)Igalia
 
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 practicesJon Peck
 
Hacking Adobe Experience Manager sites
Hacking Adobe Experience Manager sitesHacking Adobe Experience Manager sites
Hacking Adobe Experience Manager sitesMikhail Egorov
 

Ähnlich wie 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
 

Mehr von it-people

«Про аналитику и серебряные пули» Александр Подсобляев, Rambler&Co
«Про аналитику и серебряные пули» Александр Подсобляев, Rambler&Co«Про аналитику и серебряные пули» Александр Подсобляев, Rambler&Co
«Про аналитику и серебряные пули» Александр Подсобляев, Rambler&Coit-people
 
«Scrapy internals» Александр Сибиряков, Scrapinghub
«Scrapy internals» Александр Сибиряков, Scrapinghub«Scrapy internals» Александр Сибиряков, Scrapinghub
«Scrapy internals» Александр Сибиряков, Scrapinghubit-people
 
«Отладка в Python 3.6: Быстрее, Выше, Сильнее» Елизавета Шашкова, JetBrains
«Отладка в Python 3.6: Быстрее, Выше, Сильнее» Елизавета Шашкова, JetBrains«Отладка в Python 3.6: Быстрее, Выше, Сильнее» Елизавета Шашкова, JetBrains
«Отладка в Python 3.6: Быстрее, Выше, Сильнее» Елизавета Шашкова, JetBrainsit-people
 
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
«Gevent — быть или не быть?» Александр Мокров, Positive Technologiesit-people
 
«Ещё один Поиск Яндекса» Александр Кошелев, Яндекс
«Ещё один Поиск Яндекса» Александр Кошелев, Яндекс«Ещё один Поиск Яндекса» Александр Кошелев, Яндекс
«Ещё один Поиск Яндекса» Александр Кошелев, Яндекс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 — почём опиум для народа?» Игорь Новиков, Scalrit-people
 
«Gensim — тематическое моделирование для людей» Иван Меньших, Лев Константино...
«Gensim — тематическое моделирование для людей» Иван Меньших, Лев Константино...«Gensim — тематическое моделирование для людей» Иван Меньших, Лев Константино...
«Gensim — тематическое моделирование для людей» Иван Меньших, Лев Константино...it-people
 
«Тотальный контроль производительности» Михаил Юматов, ЦИАН
«Тотальный контроль производительности» Михаил Юматов, ЦИАН«Тотальный контроль производительности» Михаил Юматов, ЦИАН
«Тотальный контроль производительности» Михаил Юматов, ЦИАНit-people
 
«Детские болезни live-чата» Ольга Сентемова, Тинькофф Банк
«Детские болезни live-чата» Ольга Сентемова, Тинькофф Банк«Детские болезни live-чата» Ольга Сентемова, Тинькофф Банк
«Детские болезни live-чата» Ольга Сентемова, Тинькофф Банкit-people
 
«Микросервисы наносят ответный удар!» Олег Чуркин, Rambler&Co
«Микросервисы наносят ответный удар!» Олег Чуркин, Rambler&Co«Микросервисы наносят ответный удар!» Олег Чуркин, Rambler&Co
«Микросервисы наносят ответный удар!» Олег Чуркин, Rambler&Coit-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 Technologiesit-people
 
«PyWat. А хорошо ли вы знаете Python?» Александр Швец, Marilyn System
«PyWat. А хорошо ли вы знаете Python?» Александр Швец, Marilyn System«PyWat. А хорошо ли вы знаете Python?» Александр Швец, Marilyn System
«PyWat. А хорошо ли вы знаете Python?» Александр Швец, Marilyn Systemit-people
 
«(Без)опасный Python», Иван Цыганов, Positive Technologies
«(Без)опасный Python», Иван Цыганов, Positive Technologies«(Без)опасный Python», Иван Цыганов, Positive Technologies
«(Без)опасный Python», Иван Цыганов, Positive Technologiesit-people
 
«Python of Things», Кирилл Борисов, Яндекс
«Python of Things», Кирилл Борисов, Яндекс«Python of Things», Кирилл Борисов, Яндекс
«Python of Things», Кирилл Борисов, Яндексit-people
 
«Как сделать так, чтобы тесты на Swift не причиняли боль» Сычев Александр, Ra...
«Как сделать так, чтобы тесты на Swift не причиняли боль» Сычев Александр, Ra...«Как сделать так, чтобы тесты на Swift не причиняли боль» Сычев Александр, Ra...
«Как сделать так, чтобы тесты на Swift не причиняли боль» Сычев Александр, Ra...it-people
 
«Клиенту и серверу нужно поговорить» Прокопов Никита, Cognician
«Клиенту и серверу нужно поговорить» Прокопов Никита, Cognician«Клиенту и серверу нужно поговорить» Прокопов Никита, Cognician
«Клиенту и серверу нужно поговорить» Прокопов Никита, Cognicianit-people
 
«Кошелек или деньги: сложный выбор между памятью и процессором» Алексеенко Иг...
«Кошелек или деньги: сложный выбор между памятью и процессором» Алексеенко Иг...«Кошелек или деньги: сложный выбор между памятью и процессором» Алексеенко Иг...
«Кошелек или деньги: сложный выбор между памятью и процессором» Алексеенко Иг...it-people
 

Mehr von 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
 
«Кошелек или деньги: сложный выбор между памятью и процессором» Алексеенко Иг...
«Кошелек или деньги: сложный выбор между памятью и процессором» Алексеенко Иг...«Кошелек или деньги: сложный выбор между памятью и процессором» Алексеенко Иг...
«Кошелек или деньги: сложный выбор между памятью и процессором» Алексеенко Иг...
 

Kürzlich hochgeladen

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
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
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
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
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 

Kürzlich hochgeladen (20)

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
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
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
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
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 

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