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
67
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
Teambox: Starting and Learning
jrom
131
8.7k
Infographics Made Easy
chrislema
239
18k
Clear Off the Table
cherdarchuk
91
320k
How To Stay Up To Date on Web Technology
chriscoyier
786
250k
The Art of Programming - Codeland 2020
erikaheidi
48
13k
Fashionably flexible responsive web design (full day workshop)
malarkey
401
65k
Facilitating Awesome Meetings
lara
49
6k
Designing for Performance
lara
604
68k
Sharpening the Axe: The Primacy of Toolmaking
bcantrill
36
1.7k
Building a Scalable Design System with Sketch
lauravandoore
459
32k
Building Your Own Lightsaber
phodgson
101
6k
[Rails World 2023 - Day 1 Closing Keynote] - The Magic of Rails
eileencodes
28
1.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