Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
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
60
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
320
Node.js Streams
defly
0
160
Observable как атом приложения
defly
1
120
Featured
See All Featured
YesSQL, Process and Tooling at Scale
rocio
165
13k
KATA
mclloyd
16
12k
Fashionably flexible responsive web design (full day workshop)
malarkey
398
65k
The Illustrated Children's Guide to Kubernetes
chrisshort
32
46k
Making the Leap to Tech Lead
cromwellryan
125
8.5k
ReactJS: Keep Simple. Everything can be a component!
pedronauck
660
120k
Design by the Numbers
sachag
274
18k
Typedesign – Prime Four
hannesfritz
36
2.1k
4 Signs Your Business is Dying
shpigford
176
21k
How to name files
jennybc
65
93k
Build your cross-platform service in a week with App Engine
jlugia
226
17k
Pencils Down: Stop Designing & Start Developing
hursman
117
11k
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