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
79
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
140
Featured
See All Featured
GraphQLの誤解/rethinking-graphql
sonatard
71
11k
Dealing with People You Can't Stand - Big Design 2015
cassininazir
367
26k
The Power of CSS Pseudo Elements
geoffreycrofte
77
5.8k
Automating Front-end Workflow
addyosmani
1370
200k
How STYLIGHT went responsive
nonsquared
100
5.6k
Side Projects
sachag
455
42k
Keith and Marios Guide to Fast Websites
keithpitt
411
22k
Speed Design
sergeychernyshev
31
1k
Optimising Largest Contentful Paint
csswizardry
37
3.3k
Practical Tips for Bootstrapping Information Extraction Pipelines
honnibal
PRO
20
1.3k
Measuring & Analyzing Core Web Vitals
bluesmoon
7
490
Building Adaptive Systems
keathley
43
2.6k
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