RubyKaigi 2014
http://rubykaigi.org/2014/presentation/S-ToruKawamura
Japanese enlargement version http://www.slideshare.net/tkawa1/rubykaigi2014-hypermedia-the-missing-element-enlarged-ja
The Internet is full of Web Services, everyday more and more. Some services offer API (application programming interface) that developers use to build new applications (mash-ups). One of the most known and used technology for the machine-to-machine communication is SOAP (Simple Object Access Protocol) but in the last years we can use another paradigm, ReST (Representational State Transfer). How does it work?
Les Hazlewood, Stormpath co-founder and CTO and the Apache Shiro PMC Chair demonstrates how to design a beautiful REST + JSON API. Includes the principles of RESTful design, how REST differs from XML, tips for increasing adoption of your API, and security concerns.
Presentation video: https://www.youtube.com/watch?v=5WXYw4J4QOU
More info: http://www.stormpath.com/blog/designing-rest-json-apis
Further reading: http://www.stormpath.com/blog
Sign up for Stormpath: https://api.stormpath.com/register
Stormpath is a user management and authentication service for developers. By offloading user management and authentication to Stormpath, developers can bring applications to market faster, reduce development costs, and protect their users. Easy and secure, the flexible cloud service can manage millions of users with a scalable pricing model.
The Internet is full of Web Services, everyday more and more. Some services offer API (application programming interface) that developers use to build new applications (mash-ups). One of the most known and used technology for the machine-to-machine communication is SOAP (Simple Object Access Protocol) but in the last years we can use another paradigm, ReST (Representational State Transfer). How does it work?
Les Hazlewood, Stormpath co-founder and CTO and the Apache Shiro PMC Chair demonstrates how to design a beautiful REST + JSON API. Includes the principles of RESTful design, how REST differs from XML, tips for increasing adoption of your API, and security concerns.
Presentation video: https://www.youtube.com/watch?v=5WXYw4J4QOU
More info: http://www.stormpath.com/blog/designing-rest-json-apis
Further reading: http://www.stormpath.com/blog
Sign up for Stormpath: https://api.stormpath.com/register
Stormpath is a user management and authentication service for developers. By offloading user management and authentication to Stormpath, developers can bring applications to market faster, reduce development costs, and protect their users. Easy and secure, the flexible cloud service can manage millions of users with a scalable pricing model.
Scott Davis presented on Resource-Oriented Architecture (ROA) and REST on August 17th at IASA Denver.
Google quietly deprecated their SOAP search API at the end of 2006. While this doesn't mean that you should abandon SOAP, it does reflect a growing trend towards simpler dialects of web services. Google joins a number of popular websites (Yahoo!, Amazon, eBay, and others) that offer all of the benefits of web services without all of the complexity of SOAP.
In this talk, we look at the semantic differences between a Service-Oriented Architecture and a Resource-Oriented Architecture. We contrast RPC-centric interfaces with object-oriented interfaces. We discuss HTTP-RPC services that call themselves RESTful, and compare them to fully RESTful web services that leverage HTTP verbs like GET, POST, PUT, and DELETE. We look at RESTful implementations using Java Servlets and exploit Grails' native REST support.
A RESTful API is only truly RESTful if it uses hypermedia to tell us about all the actions that can be performed on the curent resource, allowing us to traverse the API from a single entry point.
His session looks at REST and HATEOAS (Hypermedia As The Engine Of Application State) to illustrate good service structure. Ben will use the RESTful file sharing service fdrop.it to illustrate the various examples of how this can be used.
This session is recommended for architects and senior developers alike and will give a good grounding in writing excellent, self-explanatory RESTful services.
Nick Batik introduces the concepts of the JASON REST APIs by explaining the logic behind APIs, and walking through a few practical uses for both personal and client websites. This is an informal discussion of the vocabulary and concepts to introduce the REST API to those who unfamiliar with the topic to help them prepare for a more technical understanding of the subject in order to take advantage of the possibilities.
This is a presentation which describe the big picture of the Rest API. In this presentation I simply describe the theories with practical examples. Hope this presentation will cover the overall Rest API domain.
Existem diversos aspectos que devem ser priorizados ao se escrever uma API. Bom entendimento do domínio, arquitetura ideal, boa estratégia de testes, etc. Esses são alguns dos problemas reais e prioritários existentes. JSON API é uma ótima solução para evitar a perda de tempo tentando reinventar a roda durante a definição do design das respostas de sua aplicação. Nesta apresentação, alguns exemplos de uso, considerações/vantagens e dicas de como tornar a sua aplicação compatível sem (muita) dor.
Pragmatic REST: recent trends in API designMarsh Gardiner
As presented by @mpnally and @earth2marsh at I Love APIs 2015. Slides covered API design trends, with particular attention paid to hypermedia and versioning. Note the distinction between service-oriented and data-oriented approaches on slide #5.
REST & RESTful Web Service
REST stands for Representational State Transfer
REST web services communicate over the HTTP specification, using HTTP vocabulary
If a service does not include all constraints it is not a RESTful web service.
RESTful API, nevidljiva spona koja spaja web-facing mobilne aplikacije sa online bazama podataka, server-side ishodište koje pokreće Javascript MVVM-based projekte često je nedovoljno istraženo područje čak i za iskusne programere. Ako vas zanima POST - PUT rat ili stvari poput idempotentnih nesigurnih metoda odgovore ćete pronaći u ovom predavanju.
Predavanje je održano 27. aprila 2014. godine u Beogradu na Google Code Day http://gcd.phpsrbija.rs/
Scott Davis presented on Resource-Oriented Architecture (ROA) and REST on August 17th at IASA Denver.
Google quietly deprecated their SOAP search API at the end of 2006. While this doesn't mean that you should abandon SOAP, it does reflect a growing trend towards simpler dialects of web services. Google joins a number of popular websites (Yahoo!, Amazon, eBay, and others) that offer all of the benefits of web services without all of the complexity of SOAP.
In this talk, we look at the semantic differences between a Service-Oriented Architecture and a Resource-Oriented Architecture. We contrast RPC-centric interfaces with object-oriented interfaces. We discuss HTTP-RPC services that call themselves RESTful, and compare them to fully RESTful web services that leverage HTTP verbs like GET, POST, PUT, and DELETE. We look at RESTful implementations using Java Servlets and exploit Grails' native REST support.
A RESTful API is only truly RESTful if it uses hypermedia to tell us about all the actions that can be performed on the curent resource, allowing us to traverse the API from a single entry point.
His session looks at REST and HATEOAS (Hypermedia As The Engine Of Application State) to illustrate good service structure. Ben will use the RESTful file sharing service fdrop.it to illustrate the various examples of how this can be used.
This session is recommended for architects and senior developers alike and will give a good grounding in writing excellent, self-explanatory RESTful services.
Nick Batik introduces the concepts of the JASON REST APIs by explaining the logic behind APIs, and walking through a few practical uses for both personal and client websites. This is an informal discussion of the vocabulary and concepts to introduce the REST API to those who unfamiliar with the topic to help them prepare for a more technical understanding of the subject in order to take advantage of the possibilities.
This is a presentation which describe the big picture of the Rest API. In this presentation I simply describe the theories with practical examples. Hope this presentation will cover the overall Rest API domain.
Existem diversos aspectos que devem ser priorizados ao se escrever uma API. Bom entendimento do domínio, arquitetura ideal, boa estratégia de testes, etc. Esses são alguns dos problemas reais e prioritários existentes. JSON API é uma ótima solução para evitar a perda de tempo tentando reinventar a roda durante a definição do design das respostas de sua aplicação. Nesta apresentação, alguns exemplos de uso, considerações/vantagens e dicas de como tornar a sua aplicação compatível sem (muita) dor.
Pragmatic REST: recent trends in API designMarsh Gardiner
As presented by @mpnally and @earth2marsh at I Love APIs 2015. Slides covered API design trends, with particular attention paid to hypermedia and versioning. Note the distinction between service-oriented and data-oriented approaches on slide #5.
REST & RESTful Web Service
REST stands for Representational State Transfer
REST web services communicate over the HTTP specification, using HTTP vocabulary
If a service does not include all constraints it is not a RESTful web service.
RESTful API, nevidljiva spona koja spaja web-facing mobilne aplikacije sa online bazama podataka, server-side ishodište koje pokreće Javascript MVVM-based projekte često je nedovoljno istraženo područje čak i za iskusne programere. Ako vas zanima POST - PUT rat ili stvari poput idempotentnih nesigurnih metoda odgovore ćete pronaći u ovom predavanju.
Predavanje je održano 27. aprila 2014. godine u Beogradu na Google Code Day http://gcd.phpsrbija.rs/
We need to create more reusable APIs, fewer "snowflakes" and better machine-readable APIs and descriptions. To this end, Mike Amundsen, Principal API Architect offers his "Top Ten things we need to STOP doing."
These slides focus on documentation for REST APIs. See http://idratherbewriting.com for more detail. For the video recording, see http://youtu.be/0yfNd7tzH2Q. This deep dive is the second slide deck I used in the presentation.
What is API - Understanding API SimplifiedJubin Aghara
What is API/Getting started with API/Understanding API
The document will give you a basic idea of the following:
- What is API
- Real-world examples
- REST and SOAP
- Protocol layer
- Data format (JSON and XML)
- REST HTTP API example
- Which one to go for
- Tools to get started
In this talk, we’ll discuss the benefits of the document-based data model that MongoDB offers by walking through how one can build a simple app. We'll show you how to design a full-blown RSS Aggregation service to replace the loss the world suffered when Google Reader was shutdown.
We'll dive deeper into topics, such as how to model your data and create your REST API using MongoDB, Express.js and Node.js (core components of the MEAN stack). This session will jumpstart your development knowledge of MongoDB.
Web services tutorial slides from my session at DPC 2012 in Amsterdam. In this 3-hour session we built the simplest possible service, and then extended it, looking at RPC, REST and SOAP along the way.
Every enterprise system has tons of sensitive data like database passwords or third-party API keys. Quite often people store this data openly in internal repositories, continuous integration pipeline or configuration managements systems. The bigger company the stricter security rules. It is more complex and important when you have thousands of different applications and each one has its own secrets. In this talk I am giving an overview of my personal experience on Vault technology and will show by example how you can build your own policies and move your secrets to the Vault.
Survival Strategies for API Documentation: Presentation to Southwestern Ontar...Tom Johnson
This is a presentation I gave to the Southwestern Ontario STC chapter on API documentation on Feb 2, 2015. For more details, see my blog at http://idratherbewriting.com. You can listen to the recorded presentation here: http://youtu.be/I8rGe2w1sAo.
Fundamentals of building a Restful API with Django and django-rest-framework. Intended for new developers interested in developing a REST API for their applications. Basic knowledge of Python is nice to have, but the concepts are transferable.
Presented at Vancouver Python Day 2013.
APIs REST Usables con Hypermedia por Javier Ramirez, para codemotionjavier ramirez
Con la adopción de REST, la proliferación de smartphones y tablets y el revival del JavaScript, exponer nuestra aplicación como un servicio es más importante que nunca.
Frameworks como Rails hacen muy fácil la creación de un API (más o menos) REST, pero en muchas ocasiones estas APIs se diseñan sin pensar realmente en los desarrolladores que las va a usar.
En esta charla habo sobre algunos de los puntos que pueden hacer tu API REST más amigable para desarrolladores, cubriendo áreas como el autodescubrimiento, autenticación, cabeceras, formatos, versionado, parámetros, documentación y herramientas.
Aunque comparte tema (y algunas slides) con la charla de APIs usables que preparé para el grupo de Usuarios de Ruby en Londres, gran parte del material es inédito.
Azure DocumentDB for Healthcare Integration - Part 2BizTalk360
This is the second of a three-part series. The following is the agenda for Part 2 –
Review of DocumentDB REST API
Understanding the overall problem
High-level Design
How Swagger fits in
Design and development
Next steps
Learn how to take advantage of Apigility to create APIs from scratch or to expose current functionality from an existent system. You'll learn the core API concepts, processes, functionality, logic, and in general how you can create good APIs, including documentation and all the considerations you must have.
The web has changed! Users spend more time on mobile than on desktops and expect to have an amazing user experience on both. APIs are the heart of the new web as the central point of access data, encapsulating logic and providing the same data and same features for desktops and mobiles. In this workshop, Antonio will show you how to create complex APIs in an easy and quick way using API Platform built on Symfony.
The web has changed! Users spend more time on mobile than on desktops and expect to have an amazing user experience on both. APIs are the heart of the new web as the central point of access data, encapsulating logic and providing the same data and same features for desktops and mobiles.
In this workshop, Paula and Antonio will show you how to create complex APIs in an easy and quick way using API Platform built on Symfony.
Repository: https://github.com/locastic/wscAPI2017
Go Fullstack: JSF for Public Sites (CONFESS 2012)Michael Kurz
Slides for session Go Fullstack: JSF for public sites by Michael Kurz held at the CONFESS 2012 in Leogang/Austria.
The examples for this session can be found at https://github.com/jsflive (see slides for details).
Video of this presentation can be found at http://goo.gl/EmkOP
Similar to Hypermedia: The Missing Element to Building Adaptable Web APIs in Rails (20)
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
UiPath Test Automation using UiPath Test Suite series, part 3
Hypermedia: The Missing Element to Building Adaptable Web APIs in Rails
1. HYPERMEDIA:
THE MISSING ELEMENT
to Building Adaptable Web APIs in Rails
ハイパーメディア: RailsでWeb APIをつくるには、これが足りない
Toru Kawamura
@tkawa
!
RubyKaigi 2014
2. @tkawa
Toru Kawamura
• Freelance Ruby/Rails programmer
• Technology Assistance Partner at
SonicGarden Inc.
• RESTafarian
inspired by Yohei Yamamoto (@yohei)
• Co-organizer of Sendagaya.rb
• Organizer of the
reading group of
“RESTful Web APIs”
7. • Private
• For internal use
• For SPA or dedicated
clients only
• Almost expected,
almost controllable
• Public
• For external use
• For general-purpose
clients
• Less expected,
less controllable
8. “Whether an API should be RESTful or not
depends on the requirement”
– 「WebAPIのこれまでとこれから」by @yohei
http://www.slideshare.net/yohei/webapi-36871915
11. Change is inevitable
!
Web APIs must adapt to changes
変化は避けられない
Web APIは変化に適応しなければならない
12. Two types of Change
With versioning Without versioning
Incompatible Compatible
Breaks clients Does not break clients
Breaking Change Non-Breaking Change
13. Breaking Changes are Harmful
壊す変更は有害
• Terrible user experience
ひどいユーザ体験
• Forces client developers to rewrite/redeploy code
クライアント開発者にコードの書き直し・再デプロイを強いる
• What if on …
14. Because of what?
なぜ起こるの?
With versioning Without versioning
Incompatible Compatible
Breaks clients Does not break clients
Breaking Change Non-Breaking Change
15. Many clients are built from
human-readable documentation
人間が読める説明書から作られる
クライアントがたくさんある
GET /v1/statuses?id=#{id} GET /v1/statuses?id=#{id}
17. Some clients are built from
machine-readable documentation
{
"apiVersion": "1.0.0",
"basePath": "http://
petstore.swagger.wordnik.com/api",
"resourcePath": "/store",
"produces": [
"application/json"
],
"apis": [
{
"path": "/store/order/{orderId}",
"operations": [
{
GET /v1/statuses?id=#{id} GET /v1/statuses?id=#{id}
"method": "GET",
"summary": "Find purchase order
by ID",
"notes": "For valid response
try integer IDs with value <= 5. Anything
above 5 or nonintegers will generate API
errors",
"type": "Order",
"nickname": "getOrderById",
"authorizations": {},
"parameters": [
機械が読める説明書から作られる
クライアントもある
18. GET /v2/statuses/#{id} GET /v1/statuses?id=#{id} ×Need to regenerate code
{
"apiVersion": "2.0.0",
"basePath": "http://
petstore.swagger.wordnik.com/api",
"resourcePath": "/store",
"produces": [
"application/json"
],
"apis": [
{
"path": "/store/order/{orderId}",
"operations": [
{
"method": "GET",
"summary": "Find purchase order
by ID",
"notes": "For valid response
try integer IDs with value <= 5. Anything
above 5 or nonintegers will generate API
errors",
"type": "Order",
"nickname": "getOrderById",
"authorizations": {},
"parameters": [
19. {
uber: {
Because of Coupling
version: "1.0",
data: [{
url: "http://www.ishuran.dev/notes/1",
name: "Article",
data: [
• API {
name: changes "articleBody",
should be reflected in clients
value: "First note's text"
},
{
It is name: • value: },
good "datePublished",
null
to split up explanations of the API and
{
embed name: "dateCreated",
value: "2014-them 09-11T12:into 00:31+09:00"
each API response
},
{
name: "dateModified",
value: "2014-09-11T12:00:31+09:00"
• A },
{
lot of assumptions about the API make a tight
name: "isPartOf",
rel: "collection",
coupling
url: "/notes"
密結合のせい
APIの変更がクライアントに反映されるべき
APIの説明を分割して各レスポンスに埋め込むのが良い
APIについての多大な仮定は密結合を生む
20. With versioning Without versioning
Incompatible Compatible
Breaks clients Does not break clients
Breaking Change Non-Breaking Change
because of the Coupling because of the Decoupling
21. Decoupling in a example:
FizzBuzzaaS
• by Stephen Mizell
例で見る疎結合
http://fizzbuzzaas.herokuapp.com/
http://smizell.com/weblog/2014/solving-fizzbuzz-with-hypermedia
• Server knows how to calculate
FizzBuzz for given number (<= 100)
サーバは100までの数のFizzBuzzを計算できる
• Server knows what the next FizzBuzz
will be
サーバは次のFizzBuzzが何になるか知っている
• Client wants all FizzBuzz from one to
the last in order
クライアントは1から最後まで順番にすべてのFizzBuzzが欲しい
http://sef.kloninger.com/posts/
201205fizzbuzz-for-managers.
html
22. Coupled client
密結合なクライアント
answer = HTTP.get("/v1/fizzbuzz?number=#{i}")
puts answer
end
"/v2/fizzbuzz/#{i}"
(1..1000)
(1..100).each do |i|
• Every URL and parameter is hardcoded
• Duplicates the server logic such as counting
up
すべてのURLとパラメータがハードコードされている
カウントアップのようなサーバロジックと同じことをやっている
23. Decoupled client
疎結合なクライアント
root = HTTP.get_root
answer = root.link('first').follow
puts answer
while answer.link('next').present?
answer = answer.link('next').follow
puts answer
end Link ‘next’ is the key
• No hardcoded URLs
• Client doesn’t break when changing
URLs / the restriction
ハードコードされたURLなし
URLや条件を変えてもクライアントは壊れない
24. The “API Call” metaphor is
dangerous
「APIコール」のメタファーは危険
• We need to move away from the paradigm where
a client arranges a URL and parameters in advance
and calls API (like RPC…)
URLとパラメータを用意してAPIを呼ぶというRPCのようなパラダイムから離れよう
• What a client does next should be to choose
from links in the response
== HYPERMEDIA
クライアントが次にすることはリンクから選ぶこと
これがハイパーメディア
25. This is not imaginary
but already present in HTML
これは想像上のものではなく、すでにHTMLにある
26. The HTML Web
• Web apps and websites
have been changing
constantly without
breaking browsers
• Why don’t browsers
break on the HTML Web?
There are links
in HTML
WebアプリやWebサイトはずっと変わり続けているけど
ブラウザは壊れていないのはなぜ?
http://www.youtypeitwepostit.com/messages
27. Workflow in HTML
• Web app includes a
(suggested) workflow
• Workflow is represented
by a sequence of screen
transitions
— Links and Forms
Webアプリはワークフローを含む
ワークフローは一連の画面遷移で表現される
それはリンクとフォーム
”RESTful Web APIs” p.11 Figure 1-7
28. Hypermedia show the workflow
ハイパーメディアはワークフローを示す
• Each screen includes what a
browser can do next
through links and forms like a
“menu”
• A browser chooses from the
“menu” to go to the next
step
• This is HYPERMEDIA and
exactly what FizzBuzzaaS
does
3
4
各画面は次に何ができるかのリンクやフォームの
「メニュー」を含み、ブラウザはその中から選ぶ
これがハイパーメディア
29. One more hint in a Crawler
クローラーにはもう1つヒントが
• Crawlers follow links and can submit some forms
• Crawlers understand the data in an HTML document
and their “meaning”
• How can they do that?
クローラはHTMLの中のデータと意味を理解している
https://support.google.com/webmasters/answer/99170 どうやって?
30. Microdata
<div itemscope itemtype="http://schema.org/Person">
My name is <span itemprop="name">Bob Smith</span>
but people call me <span itemprop="nickname">Smithy</span>.
Here is my home page:
<a href="http://www.example.com" itemprop="url">www.example.com</a>
I live in Albuquerque, NM and
work as an <span itemprop="title">engineer</span>
at <span itemprop="affiliation">ACME Corp</span>.
</div>
• Mechanism that embeds structured data within an HTML
document
• Document structure can change without changing data
• Connects data with a URL that roughly represents
the “meaning of data” (this is also a kind of link)
Microdataは構造化データをHTMLに埋め込むしくみ
URLに結びつけることで大まかな「データの意味」も表す
31. Microdata
<div itemscope itemtype="http://schema.org/Person">
My name is <span itemprop="name">Bob Smith</span>
but people call me <span schema.itemprop="org
nickname">Smithy</span>.
Here is my home page:
<a href="is the http://standard www.example.vocabulary com" itemprop="promoted url">www.example.I live in Albuquerque, NM and
by
com</a>
work as an Bing, <span itemprop="Google, title">at <span itemprop="affiliation">Yahoo! engineer</span>
ACME Corp</and Yandex
span>.
</div>
• Mechanism that embeds structured data within an HTML
document
• Document structure can change without changing data
• Connects data with a URL that roughly represents
the “meaning of data” (this is also a kind of link)
http://getschema.org/index.php/Main_Page
32. You could build a Web API in HTML
HTMLでWeb APIを作ることもできる
var user = document.getItems('http://schema.org/Person')[0];
var name = user.properties['name'][0].itemValue;
alert('Hello ' + name + '!');
• “Microdata DOM API” allows clients to extract data from HTML
http://www.w3.org/TR/microdata/#using-the-microdata-dom-api
Microdata DOM APIでHTMLからデータを抽出できる
• Available in JavaScript: https://github.com/termi/Microdata-JS
• There are also some specs for translating Microdata into JSON
MicrodataからJSONに変換もできる
• HTML’s great advantage is that it has links and forms built-in
HTMLはリンクとフォームを持っているのが大きなアドバンテージ
33. But you probably want a
JSON Web API…
でもたぶんJSON Web APIが欲しいよね
data link form
HTML
+Microdata ✓✓ ✓ ✓
JSON ✓ - -
✓✓: including “meaning of data”
• You have to fill in links and forms
(also the meanings of data, if possible)
リンクとフォームを埋めればいい(できればデータの意味も)
34. Links and Forms in JSON
• Use a JSON-based
format that can represent
links and forms
• There are other formats
Siren, Collection+JSON,
Mason, Verbose, etc
data link form
JSON ✓ - -
JSON
+Link header ✓ ✓ -
HAL ✓ ✓ -
JSON-LD ✓✓ ✓ -
JSON-LD
+Hydra ✓✓ ✓ ✓
UBER ✓ ✓ ✓
リンクとフォームを表現できる
JSONベースのフォーマットがある
✓✓: including “meaning of data”
36. Hypermicrodata gem
https://github.com/tkawa/hypermicrodata
• Translate HTML into JSON on Server-side
• Extract not only Microdata but also links and
forms from HTML
• Generate a JSON-based format that naturally fits
with an explanation of meaning of data
サーバサイドでHTMLをJSONに変換
Microdataだけではなく
リンクとフォームもHTMLから抽出
データの意味も表しやすい形で
JSONベースのフォーマットを生成
37. Design procedure in Rails with
Hypermicrodata gem
Hypermicrodata gemを使ったRailsによる設計手順
1. Design resources
2. Draw a state diagram
3. Connect names of data with corresponding URLs
4. Write HTML templates (Haml, Slim, etc) with
Microdata markup
1. リソース設計
2. 状態遷移図を描く
3. データの名前を対応するURLに結びつける
4. HTMLテンプレートを書き
Microdataでマークアップ
(Then, write profiles and explanations that are not defined in
schema.org, if necessary)
38. 1. Design resources
column name short description type
text content text of note text
published_at published time of note datetime
(id, created_at, updated_at) (auto-generated)
$ rails g model Note text:text published_at:datetime
model: Note
controller: NotesController
routing: resources :notes
39. 2. Draw a state diagram
Begin with Collection & Member Resource pattern of Rails (API ver.)
item
collection
Collection Member
create*†
update*, delete*
* unsafe
† non-idempotent
40. Collection
of Note
Note
(text, published_at,
created_at,
updated_at, id)
item
collection
create*†
update*, delete*,
* unsafe
† non-idempotent
publish*
next, prev
Home
notes home
41. 3. Connect names of data with
corresponding URLs
Collection of Note http://schema.org/ItemList
Note http://schema.org/Article
text http://schema.org/articleBody
published_at http://schema.org/datePublished
created_at http://schema.org/dateCreated
updated_at http://schema.org/dateModified
id (No need because each note has its own URL)
Home http://schema.org/SiteNavigationElement
45. 3 Pros of this design procedure
• DRY
• When providing both HTML and JSON
• Awareness of links and forms
• Framing the API as an HTML Web app gets you
focused on these state transition
• Constraints
• “Constraints are liberating”
この設計手順の3つのメリット
HTMLとJSON両方提供するならDRY
APIをWebアプリと同じように考えることで状態遷移に着目し
リンクとフォームを意識できる
「制約は自由をもたらす」
46. If you want to write only JSON,
you should keep in mind
もしJSONだけを書くときは注意すること
• To stay focused on the link/form pattern:
• Draw a state diagram
リンク・フォームを意識するために
状態遷移図を描きましょう
• To keep your API decoupled:
• Use view templates or representers such as Jbuilder/RABL
instead of model.to_json
疎結合のために、model.to_jsonはやめて
ビューテンプレートを使いましょう
• Use a JSON-based format with links and forms
リンクとフォームを持ったJSONベースのフォーマットを使いましょう
• In addition, it is better to use standard names such as schema.org
schema.orgのような標準名を使うとさらに良いです
48. Conclusion:
Design Your Web API the same way
as an HTML Web App
結論: Web APIはHTML Webアプリと同じように設計しよう
• A Web API is nothing special, It just has a different
representation format
Web APIは特別なものではなく、ただ表現フォーマットが違うだけ
• Awareness of state transitions by drawing a
diagram will remind you of links and forms
状態遷移図を描いて状態遷移を意識することで、リンクやフォームを忘れずにすむ
49. Finally
• Unfortunately, no de-facto standard JSON format,
client implementations, libraries, etc
残念ながら、デファクトスタンダードがない
• We can do better by focusing on the principles and
constraints of REST
RESTの制約・原則を意識するともっとうまくできる
• Hypermedia is one of the most important elements of
REST, and a key step toward building Web APIs
adaptable to change
ハイパーメディアはRESTの最も重要な要素で
変化に適応できるWeb APIへの重要なステップ
50. Build a Better & Adaptable Web API.
Thank you for your attention.
References
• L. Richardson & M. Amundsen “RESTful Web APIs” (O’Reilly)
• 山本陽平 “Webを支える技術” (技術評論社)
• Designing for Reuse: Creating APIs for the Future
http://www.oscon.com/oscon2014/public/schedule/detail/34922
• API Design Workshop 配布資料
http://events.layer7tech.com/tokyo-wrk
• https://speakerdeck.com/zdne/robust-mobile-clients-v2
• http://www.slideshare.net/yohei/webapi-36871915
• http://smizell.com/weblog/2014/solving-fizzbuzz-with-hypermedia
• 山口 徹 “Web API デザインの鉄則” WEB+DB PRESS Vol.82