Lock in $30 Savings on PRO—Offer Ends Soon! ⏳
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Hypermedia API (MinskJS version)
Search
Artem Bey
March 15, 2016
0
82
Hypermedia API (MinskJS version)
Artem Bey
March 15, 2016
Tweet
Share
More Decks by Artem Bey
See All by Artem Bey
Модульное React/Redux приложение
defly
1
330
Node.js Streams
defly
0
170
Observable как атом приложения
defly
1
150
Featured
See All Featured
A better future with KSS
kneath
240
18k
Optimizing for Happiness
mojombo
379
70k
Build The Right Thing And Hit Your Dates
maggiecrowley
38
3k
Leading Effective Engineering Teams in the AI Era
addyosmani
8
1.2k
The Invisible Side of Design
smashingmag
302
51k
Building Adaptive Systems
keathley
44
2.9k
Templates, Plugins, & Blocks: Oh My! Creating the theme that thinks of everything
marktimemedia
31
2.6k
The Pragmatic Product Professional
lauravandoore
37
7k
Building a Modern Day E-commerce SEO Strategy
aleyda
45
8.1k
Principles of Awesome APIs and How to Build Them.
keavy
127
17k
Building a Scalable Design System with Sketch
lauravandoore
463
34k
Documentation Writing (for coders)
carmenintech
76
5.2k
Transcript
Hypermedia API 1
Артём Бей @defly_self Fullstack dev в Trinity Mirror 2
3
Representational State Transfer “Architectural Styles and the Design of Network-based
Software Architectures” Roy Fielding 4
REST это архитектурный стиль для распределенных гипермедиа систем. 5
REST != HTTP 6
Ресурс http://…/resource <xml> <entity/> </xml> { entity: {…} } 7
http://…/resource <xml> <entity/> </xml> { entity: {…} } представление представление
ресурс идентификатор документ картинка процесс … 8
Richardson Maturity Model 9
REST уровня 0 POST /api { "do": "createOrder", "params": {
"count": 2 } } POST /api { "do": "cancelOrder", "params": { "id": "34xzfha834flksd34" } } 200 OK { "success": true, "res": { "id": "f239sdk237sdf438" } } 200 OK { "success": false, "error": { "code": 666, "message": "because fk u thats why" } } /api 10
REST уровня 1 POST /users {…} 200 OK { "success":
true, "res": { "id": "f239sdk237sdf438" } } 200 OK { "success": false, "error": { "code": 40000, "message": "not valid req" } } /users POST /users/1 {…} POST /orders {…} /users/1 /orders 11
REST уровня 2 12
REST уровня 2 Используем HTTP по спецификации 13
GET POST PUT DELETE OPTIONS HEAD PATCH … 14
15
200 OK { "success": false, "error": { "code": 666, "message":
"because fk u thats why" } 16
400 Bad Request 401 Unauthorized 403 Forbidden 404 Not Found
402 Payment Required 409 Conflict … 17
418 I’m a teapot P.S. Больше статусов на: http://httpstatusdogs.com/ https://http.cat/
18
/users /orders /profile … GET POST PUT DELETE OPTIONS HEAD
PATCH … 200 201 … 300 301 … 400 401 … 500 501 … покроют все ваши кейсы 19
REST уровень 3 20
Гипертекст 21
HATEOAS Hypermedia As The Engine Of Application State 22
представление ресурса = данные + контролы 23
GET /feed 200 OK { "data": [ { "title": "...",
"links": { "details": "http://..." } }, .... ], "links": { "self": "http://...", "first": "http://...", "prev": "http://...", "next": "http://...", "last": "http://..." } } 24 << < > >>
GET /feed?min_id=100500 200 OK { "data": [ { "title": "...",
"links": { "details": “http://..." } }, .... ], "links": { "self": "http://...", "first": "http://...", "prev": "http://...", "next": "http://...", "last": "http://..." } } 25 << < > >>
GET /films/themartian 200 OK { "data": { "title": "Марсианин", "description":
"Как Мэт Дэймон выращивал картошку на Марсе", "duration": 140, "poster": "https://s3.amazon.com/buckets/23aGd23asdsf.png" }, "links": { "self": "http://.../themartian", "booking": "http://.../themartian/bookings" } } 26
OPTIONS /films/themartian/bookings 204 No Content Allow: HEAD,GET,POST,OPTIONS 27 GET /films/themartian
200 OK { "data": { "title": "Марсианин", "description": "Как Мэт Дэймон выращивал картошку на Марсе", "duration": 140, "poster": "https://s3.amazon.com/buckets/23aGd23asdsf.png" }, "links": { "self": "http://.../themartian", "booking": "http://.../themartian/bookings" } }
POST /films/themartian/bookings { count: 3 } 201 Created Location: http://..../bookings/1
28
GET /films/themartian/bookings/1 200 OK { "data": { "count": 3, "date":
"Tue Nov 03 2015 21:45:55 GMT+0200 (EET)", "status": "waiting" }, "links": { "self": "http://..../bookings/1", "cancel": "http://..../bookings/1/cancel", "pay": "http://.../bookings/1/pay" } } 29
Стейт-машина Переходим в новые состояния по ссылке 30
Состояние вычисляется в одном месте
Забываем о формировании URL на клиенте
Распределённые приложения "links": { "self": "http://...", "upload": "http://...s3.amazonaws.com/", "pay": "https://api.stripe.com/v1/charges/",
"convert": "https://...docx2pdf.mcrsrvs.com/" }
Discoverability
Developer Experience
Некоторые приёмы • Безопасные и идемпотентные операции • Кеширование неизменяемых
ресурсов • X- заголовки • Вендорные типы данных (application/ vnd.myapi.basket.v1+json) 36
Вопросы к HATEOAS 37
В JSON нет ссылок и форм Есть спецификации: HAL, Siren,
json:api 38
Нужна ли теперь документация? Нужна. REST для машин. 39
Слишком академично или много лишнего Не нужно реализовывать спецификации в
полном объёме 40
Почитать • https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm • http://roy.gbiv.com/untangled/2008/rest-apis-must-be- hypertext-driven • http://martinfowler.com/articles/ richardsonMaturityModel.html •
http://www.jeffknupp.com/blog/2014/06/03/why-i-hate- hateoas • http://timelessrepo.com/haters-gonna-hateoas
Спасибо, задавайте вопросы! 42