SlideShare a Scribd company logo
Commanding a More
Meaningful REST API
Brandon Mueller
@fatmuemoo
fatmuemoo.com
Panhandle Web Tech
http://www.meetup.com/Panhandle-Web-Tech/
6:30 on the Third Tuesday of the Month
@ Firebrand Media
229 East Martin St, Suite 5
Martinsburg, WV 25401
What is covered
● API Basics
● API Good Practices
● CRUD API Examples
● Commanding API Explained
● Commanding API Examples
● CRUD and Commanding Coexistence
What is NOT covered
● Security or Authentication
● HAL or HATEOAS
● CQRS* or DDD*
● Nitty-Gritty Implementation Details
● The farm is a home to people, places and things. These
are the nouns in your API
● Nouns are also called resources or entities.
● The nouns are represented in your API by the URL.
● Like things inside of your farm, you can do things with
your resources.
● You tell your nouns to do things via verbs.
● The HTTP spec come with built in verbs, among these
are GET, PUT, POST, and DELETE
● These verbs are great for CRUD functionality.
Your API is Like a Farm
HTTP verb Resource URL Explanation
POST /barns Creates a new barn
GET /barns Gets all the barns on
the farm
GET /barns/11 Gets the barn with
the ID of 11
PUT /barns/11 Updates the barn
with the ID of 11
DELETE /barns/11 Deletes the barn
with the ID of 11
C
R
U
D
Some Good Ideas to Follow:
1. ALWAYS use plural nouns - keeps it simple
2. Nest resources!
/barns/30/animals
/barns/30/stables/1/animals
3. Handle errors with a standardized response body
4. Use the standard HTTP verbs
5. Use appropriate HTTP headers
6. Use appropriate HTTP response codes
Read The Spec
Status Codes: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Headers: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
Status Codes In a Nutshell
● 2xx - It worked
● 3xx - Go away
● 4xx - The client messed up
● 5xx - The server messed up
Idempotent/Safe Methods
Idempotent methods can be applied over and
over again and always have the same effect on
the resource
Safe methods do not have any modifying effect
on the resource
Idempotent/Safe Methods
Method Idempotent Safe
GET YES YES
POST NO NO
PUT YES NO
DELETE YES NO
PATCH NO NO
HEAD YES YES
OPTIONS YES YES
POST v PUT v PATCH
● POST is used to create an entity
● PUT is used to update an entity where you
must send the entire representation of the
entity as you wish for it to be stored
● PATCH is used to update an entity where
you send only the fields that need updated
CRUDy Workflow
Client
Application Server
Client uses HTTP POST, GET, PUT and DELETE
Verbs to CREATE, READ, UPDATE and DELETE
Create an Animal
$.post({
url: '/api/animals,
data: {
name: 'Bob',
}
});
Server returns “201 created” status and a
JSON representation of the newly created
street, as well a link to the street
{
id: 30,
name: 'Bob',
_links: { self: '/api/animals/30' }
}
Read Animals
$.get({
url: '/api/animals,
});
Server returns “200 OK”, and a JSON
representation of the streets
{
page: 1,
total_pages: 10,
items: [
{id: 30, 'name': 'Bob', _links: { self: '/api/animals/30' },
....
]
}
Update an Animal
$.put({
url: '/api/animals/30',
data: {
name: 'Robert'
}
});
Server returns “200 OK” status and a
JSON representation of the street,
{
id: 30,
name: 'Robert',
_links: { self: '/api/animals/30' }
}
NOTE: Most implementations of the PUT verb require the entire representation of the entity.
See HTTP PATCH verb for updating with a partial representation of the entity.
Delete an Animal
$.ajax({
type: 'DELETE',
url: '/api/animals/30'
});
Server returns a ‘204 No Content’
status and should not have a
response body. Any further GET requests to /api/animals/30 should return a ‘404
Not Found’ status
Awesome!
● We can create some really awesome APIs
where we can create, read, update, and
delete entities in a standard way.
● These standards have lead to some very
powerful libraries that can help you create
and consume CRUD APIs
Where is the Business Logic?
Client
Application Server
Client uses HTTP POST, GET, PUT and DELETE
Verbs to CREATE, READ, UPDATE and DELETE
● Sometimes this is what we want
● When we create APIs we don’t always know the specific
use case
● We just want to expose the data
Business Logic on The Client Side?
● A CRUD API is a really good way to expose
meaningful data in a flexible way
● You make few assumptions on how the data
will be displayed or used
● Fosters innovation and allows for really
interesting clients
Really? Client Side?
● Stopping at CRUD functionality limits what
your API can actually do
● Complex business problems should not rely
on client side implementations
● Only implementing CRUD functionality can
lead to an API that doesn't know what it
does, it only knows about the data it stores
Wait, This SUCKS!
How do you go beyond simply creating,
reading, updating, and deleting things?
● How do you reroof a barn?
● Clean a stable?
● Castrate a goat?
Commanding API
Take a resources, add a command (verb) to the
end, send data for that command in POST
HTTP verb
○ POST /barns/11/reroof
○ POST /barns/1/stable/2/clean
○ POST /goats/133/castrate
Command or Resource?
Command Resource
Verb Noun
You can only POST and
sometimes GET never PUT or
DELETE
All HTTP verbs are OK
Once a command has been
submitted, it cannot be
removed or updated (read only)
Most resources can be
removed or updated
HTTP
Verb
Command URL Explained
POST /barns/11/reroof Sends the command to reroof
barn 11
GET /barns/11/reroof Meta data about reroof
command and barn 11. Maybe
the last time it was reroofed,
whether or not we are currently
reroofing
GET /barns/11/reroof/{cmdID} Meta data about the specific
instance of the reroof
command
Commands Are NOT First Class Citizens
POST /createBarn
POST /barns
POST /updateBarn
PUT /barns/1
POST /cleanBarn
POST /barns/1/clean
Example: Reroof a barn
$.post({
url: '/barns/11/reroof'
});
Server responds with ‘200 OK’ status, and meta
data about the command:
{cmd_id: '123e4567-e89b-12d3-a456-426655440000'}
In this example, the command is executed and
completed within the lifecycle of the HTTP request.
Wait: That’s Not The Whole Story
We use a Commanding Pattern because we
are performing an action on a resource. In the
real word, these actions can take time.
Reroof a Barn
$.post({
url: '/barns/11/reroof'
});
Server responds with ‘202 Accepted’
status, and meta data about the
command:
{
cmd_id: '123e4567-e89b-12d3-a456-426655440000',
_links: {
status: '/barns/11/reroof/123e4567-e89b-12d3-a456-426655440000'
}
}
Reroof a Barn; Check Status
$.get({
url: '/barns/11/reroof/123e4567-e89b-12d3-a456-426655440000'
});
Server responds with ‘200 OK’ status and
data about the command
{
shingles_complete: 5,
out_of: 1024,
}
Client
Application Server
Client sends
POST command
Clients Checks
Status URL until
complete, updating
UI with progress
What About Querying?
● Sometimes a query request cannot be
completed in a reasonable amount of time
● Sometimes you have to send a POST
payload in order to send enough data for the
server to process a query
● This is a special case of a command
Querying
$.post({
url: '/chickens/search'
data: {
type: 'heritage'
egg_color: 'blue',
age: 'young'
}
}); Just like a command, we return ‘202 Accepted’ status,
and return some meta data:
{
cmd_id: '7ecba660-5032-11e4-916c-0800200c9a66',
_links: {
results: '/chickens/searchResults/7ecba660-5032-11e4-916c-0800200c9a66',
status: '/chickens/search/7ecba660-5032-11e4-916c-0800200c9a66',
}
}
Getting Results...
If you try to hit the results link before the results are
complete:
● the server will return the search results in whatever
state it is available
● return a ‘203 Non-Authoritative Information’
● a link to the status url
● and a Retry-After header
Using this pattern, you can expire content and return the
203 status code to tell the client to refresh the content
Getting Results...
HTTP Request
Do we have
the
resource?
203 With a Retry
After Header
And Status URL
200 OK
Has the data
expired or
still being
created?
Check
Status
Status
Is it done?
Separating Command and
Queries...
Developing expressive and
meaningful endpoints...
Using nouns and verbs that
reflect what your API
actually does...
Proudly Inspired by Others
ENTERING
BUZZWORD ZONE!
CQRS Martin Fowler
CQRS stands for Command Query Responsibility
Segregation. It's a pattern that I first heard described by
Greg Young. At its heart is a simple notion that you can use
a different model to update information than the model you
use to read information. This simple notion leads to some
profound consequences for the design of information
systems.
http://martinfowler.com/bliki/CQRS.html
DDD Wikipedia
Domain-driven design (DDD) is an approach to software
development for complex needs by connecting the
implementation to an evolving model. The premise of
domain-driven design is the following:
1. Placing the project's primary focus on the core domain
and domain logic.
2. Basing complex designs on a model of the domain.
3. Initiating a creative collaboration between technical and
domain experts to iteratively refine a conceptual model
that addresses particular domain problems.
http://en.wikipedia.org/wiki/Domain-driven_design
DDD and CQRS in My Own Words...
● Domain Driven Design is a philosophy and methodology
in which your domain model should represent the
business problems that your app is actually solving
● Command Query Responsibility Segregation is the
strategy of separating commands from queries, as
opposed to CRUD functionality which is represented in
the same object. CQRS can help you follow the SOLID
principle
DDD - Know Your Role!
● Talk to stakeholders and domain
experts
● Strive for a ubiquitous language
● Know the context in which your
API endpoints will be used
● Use this knowledge to develop
your endpoints
CRUD API Commanding API
Create a Product POST /products POST /products
Update a Product PUT /products/{id} PUT /products/{id}
Mark Product as Active PUT /products/{id} POST /products/{id}/activate
Describe a Product PUT /products/{id} POST /products/{id}/describe
Order a Product ???? POST /products/{id}/order
Markdown a Product PUT /products/{id} POST /products/{id}/markdown
Review a products POST /products/{id}/reviews POST /products/{id}/review
Mark product as out of stock PUT /products/{id} POST /products/{id}/outOfStock
CRUDy v Commandy
CQRS and CRUD, Mutually
Exclusive?
Commands Are NOT First Class Citizens
POST /createBarn
POST /barns
POST /updateBarn
PUT /barns/1
POST /cleanBarn
POST /barns/1/clean
CQRS and CRUD Can Coexist
PUT or PATCH is just an update command BUT:
● Be very selective with what is allowed to be updated
● It is not always appropriate to expose update
functionality for a particular object or property
● If another command updates a property, updating that
property directly probably shouldn’t be allowed
DELETE is a special use case command too
Brandon Mueller
@fatmuemoo
fatmuemoo.com
END
BUZZWORDS

More Related Content

What's hot

Design patterns for microservice architecture
Design patterns for microservice architectureDesign patterns for microservice architecture
Design patterns for microservice architecture
The Software House
 
REST API
REST APIREST API
REST API
Tofazzal Ahmed
 
Enforcing Your Organization's API Design Standards with SwaggerHub
Enforcing Your Organization's API Design Standards with SwaggerHubEnforcing Your Organization's API Design Standards with SwaggerHub
Enforcing Your Organization's API Design Standards with SwaggerHub
SmartBear
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
Young-Ho Cho
 
Domain Driven Design: Zero to Hero
Domain Driven Design: Zero to HeroDomain Driven Design: Zero to Hero
Domain Driven Design: Zero to Hero
Fabrício Rissetto
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
Ryan Riley
 
Domain Driven Design(DDD) Presentation
Domain Driven Design(DDD) PresentationDomain Driven Design(DDD) Presentation
Domain Driven Design(DDD) Presentation
Oğuzhan Soykan
 
DDD Tactical Design with Clean Architecture - Ivan Paulovich
DDD Tactical Design with Clean Architecture - Ivan PaulovichDDD Tactical Design with Clean Architecture - Ivan Paulovich
DDD Tactical Design with Clean Architecture - Ivan Paulovich
Ivan Paulovich
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
Amazon Web Services
 
Architecture: Microservices
Architecture: MicroservicesArchitecture: Microservices
Architecture: Microservices
Amazon Web Services
 
Redux Toolkit - Quick Intro - 2022
Redux Toolkit - Quick Intro - 2022Redux Toolkit - Quick Intro - 2022
Redux Toolkit - Quick Intro - 2022
Fabio Biondi
 
Domain Driven Design (Ultra) Distilled
Domain Driven Design (Ultra) DistilledDomain Driven Design (Ultra) Distilled
Domain Driven Design (Ultra) Distilled
Nicola Costantino
 
Microservices Docker Kubernetes Istio Kanban DevOps SRE
Microservices Docker Kubernetes Istio Kanban DevOps SREMicroservices Docker Kubernetes Istio Kanban DevOps SRE
Microservices Docker Kubernetes Istio Kanban DevOps SRE
Araf Karsh Hamid
 
How to test infrastructure code: automated testing for Terraform, Kubernetes,...
How to test infrastructure code: automated testing for Terraform, Kubernetes,...How to test infrastructure code: automated testing for Terraform, Kubernetes,...
How to test infrastructure code: automated testing for Terraform, Kubernetes,...
Yevgeniy Brikman
 
Domain Driven Design
Domain Driven Design Domain Driven Design
Domain Driven Design
Araf Karsh Hamid
 
A Pattern Language for Microservices
A Pattern Language for MicroservicesA Pattern Language for Microservices
A Pattern Language for Microservices
Chris Richardson
 
Monitoring With Prometheus
Monitoring With PrometheusMonitoring With Prometheus
Monitoring With Prometheus
Agile Testing Alliance
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
ivpol
 
Why Microservices
Why MicroservicesWhy Microservices
Why Microservices
Amazon Web Services
 
RESTful API - Best Practices
RESTful API - Best PracticesRESTful API - Best Practices
RESTful API - Best Practices
Tricode (part of Dept)
 

What's hot (20)

Design patterns for microservice architecture
Design patterns for microservice architectureDesign patterns for microservice architecture
Design patterns for microservice architecture
 
REST API
REST APIREST API
REST API
 
Enforcing Your Organization's API Design Standards with SwaggerHub
Enforcing Your Organization's API Design Standards with SwaggerHubEnforcing Your Organization's API Design Standards with SwaggerHub
Enforcing Your Organization's API Design Standards with SwaggerHub
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Domain Driven Design: Zero to Hero
Domain Driven Design: Zero to HeroDomain Driven Design: Zero to Hero
Domain Driven Design: Zero to Hero
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Domain Driven Design(DDD) Presentation
Domain Driven Design(DDD) PresentationDomain Driven Design(DDD) Presentation
Domain Driven Design(DDD) Presentation
 
DDD Tactical Design with Clean Architecture - Ivan Paulovich
DDD Tactical Design with Clean Architecture - Ivan PaulovichDDD Tactical Design with Clean Architecture - Ivan Paulovich
DDD Tactical Design with Clean Architecture - Ivan Paulovich
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
Architecture: Microservices
Architecture: MicroservicesArchitecture: Microservices
Architecture: Microservices
 
Redux Toolkit - Quick Intro - 2022
Redux Toolkit - Quick Intro - 2022Redux Toolkit - Quick Intro - 2022
Redux Toolkit - Quick Intro - 2022
 
Domain Driven Design (Ultra) Distilled
Domain Driven Design (Ultra) DistilledDomain Driven Design (Ultra) Distilled
Domain Driven Design (Ultra) Distilled
 
Microservices Docker Kubernetes Istio Kanban DevOps SRE
Microservices Docker Kubernetes Istio Kanban DevOps SREMicroservices Docker Kubernetes Istio Kanban DevOps SRE
Microservices Docker Kubernetes Istio Kanban DevOps SRE
 
How to test infrastructure code: automated testing for Terraform, Kubernetes,...
How to test infrastructure code: automated testing for Terraform, Kubernetes,...How to test infrastructure code: automated testing for Terraform, Kubernetes,...
How to test infrastructure code: automated testing for Terraform, Kubernetes,...
 
Domain Driven Design
Domain Driven Design Domain Driven Design
Domain Driven Design
 
A Pattern Language for Microservices
A Pattern Language for MicroservicesA Pattern Language for Microservices
A Pattern Language for Microservices
 
Monitoring With Prometheus
Monitoring With PrometheusMonitoring With Prometheus
Monitoring With Prometheus
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 
Why Microservices
Why MicroservicesWhy Microservices
Why Microservices
 
RESTful API - Best Practices
RESTful API - Best PracticesRESTful API - Best Practices
RESTful API - Best Practices
 

Similar to Cqrs api v2

Cqrs api
Cqrs apiCqrs api
Cqrs api
Brandon Mueller
 
RefCard RESTful API Design
RefCard RESTful API DesignRefCard RESTful API Design
RefCard RESTful API Design
OCTO Technology
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
REST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterREST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in Codeigniter
Sachin G Kulkarni
 
A RESTful introduction
A RESTful introductionA RESTful introduction
A RESTful introduction
Daniel Toader
 
BDD to the Bone: Using Behave and Selenium to Test-Drive Web Applications
BDD to the Bone: Using Behave and Selenium to Test-Drive Web ApplicationsBDD to the Bone: Using Behave and Selenium to Test-Drive Web Applications
BDD to the Bone: Using Behave and Selenium to Test-Drive Web Applications
Patrick Viafore
 
JAX-RS. Developing RESTful APIs with Java
JAX-RS. Developing RESTful APIs with JavaJAX-RS. Developing RESTful APIs with Java
JAX-RS. Developing RESTful APIs with Java
Jerry Kurian
 
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
Evan Mullins
 
Timings API: Performance Assertion during the functional testing
 Timings API: Performance Assertion during the functional testing Timings API: Performance Assertion during the functional testing
Timings API: Performance Assertion during the functional testing
PetrosPlakogiannis
 
Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.
Mario Cardinal
 
Introduction To REST
Introduction To RESTIntroduction To REST
Introduction To REST
rainynovember12
 
Web Scraping with PHP
Web Scraping with PHPWeb Scraping with PHP
Web Scraping with PHP
Matthew Turland
 
HTTP Basics Demo
HTTP Basics DemoHTTP Basics Demo
HTTP Basics Demo
InMobi Technology
 
REST-API introduction for developers
REST-API introduction for developersREST-API introduction for developers
REST-API introduction for developers
Patrick Savalle
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
Lorna Mitchell
 
Crafting APIs
Crafting APIsCrafting APIs
Crafting APIs
Tatiana Al-Chueyr
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
07.pallav
 
Great APIs - Future of Your Progress App
Great APIs - Future of Your Progress AppGreat APIs - Future of Your Progress App
Great APIs - Future of Your Progress App
Gabriel Lucaciu
 
CICONF 2012 - Don't Make Me Read Your Mind
CICONF 2012 - Don't Make Me Read Your MindCICONF 2012 - Don't Make Me Read Your Mind
CICONF 2012 - Don't Make Me Read Your Mind
ciconf
 
Pinterest like site using REST and Bottle
Pinterest like site using REST and Bottle Pinterest like site using REST and Bottle
Pinterest like site using REST and Bottle
Gaurav Bhardwaj
 

Similar to Cqrs api v2 (20)

Cqrs api
Cqrs apiCqrs api
Cqrs api
 
RefCard RESTful API Design
RefCard RESTful API DesignRefCard RESTful API Design
RefCard RESTful API Design
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
Switch to Backend 2023
 
REST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterREST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in Codeigniter
 
A RESTful introduction
A RESTful introductionA RESTful introduction
A RESTful introduction
 
BDD to the Bone: Using Behave and Selenium to Test-Drive Web Applications
BDD to the Bone: Using Behave and Selenium to Test-Drive Web ApplicationsBDD to the Bone: Using Behave and Selenium to Test-Drive Web Applications
BDD to the Bone: Using Behave and Selenium to Test-Drive Web Applications
 
JAX-RS. Developing RESTful APIs with Java
JAX-RS. Developing RESTful APIs with JavaJAX-RS. Developing RESTful APIs with Java
JAX-RS. Developing RESTful APIs with Java
 
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
 
Timings API: Performance Assertion during the functional testing
 Timings API: Performance Assertion during the functional testing Timings API: Performance Assertion during the functional testing
Timings API: Performance Assertion during the functional testing
 
Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.
 
Introduction To REST
Introduction To RESTIntroduction To REST
Introduction To REST
 
Web Scraping with PHP
Web Scraping with PHPWeb Scraping with PHP
Web Scraping with PHP
 
HTTP Basics Demo
HTTP Basics DemoHTTP Basics Demo
HTTP Basics Demo
 
REST-API introduction for developers
REST-API introduction for developersREST-API introduction for developers
REST-API introduction for developers
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
 
Crafting APIs
Crafting APIsCrafting APIs
Crafting APIs
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Great APIs - Future of Your Progress App
Great APIs - Future of Your Progress AppGreat APIs - Future of Your Progress App
Great APIs - Future of Your Progress App
 
CICONF 2012 - Don't Make Me Read Your Mind
CICONF 2012 - Don't Make Me Read Your MindCICONF 2012 - Don't Make Me Read Your Mind
CICONF 2012 - Don't Make Me Read Your Mind
 
Pinterest like site using REST and Bottle
Pinterest like site using REST and Bottle Pinterest like site using REST and Bottle
Pinterest like site using REST and Bottle
 

Recently uploaded

Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
fredae14
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
David Brossard
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Jeffrey Haguewood
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
SitimaJohn
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 

Recently uploaded (20)

Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 

Cqrs api v2

  • 1. Commanding a More Meaningful REST API Brandon Mueller @fatmuemoo fatmuemoo.com
  • 2. Panhandle Web Tech http://www.meetup.com/Panhandle-Web-Tech/ 6:30 on the Third Tuesday of the Month @ Firebrand Media 229 East Martin St, Suite 5 Martinsburg, WV 25401
  • 3. What is covered ● API Basics ● API Good Practices ● CRUD API Examples ● Commanding API Explained ● Commanding API Examples ● CRUD and Commanding Coexistence
  • 4. What is NOT covered ● Security or Authentication ● HAL or HATEOAS ● CQRS* or DDD* ● Nitty-Gritty Implementation Details
  • 5. ● The farm is a home to people, places and things. These are the nouns in your API ● Nouns are also called resources or entities. ● The nouns are represented in your API by the URL. ● Like things inside of your farm, you can do things with your resources. ● You tell your nouns to do things via verbs. ● The HTTP spec come with built in verbs, among these are GET, PUT, POST, and DELETE ● These verbs are great for CRUD functionality. Your API is Like a Farm
  • 6. HTTP verb Resource URL Explanation POST /barns Creates a new barn GET /barns Gets all the barns on the farm GET /barns/11 Gets the barn with the ID of 11 PUT /barns/11 Updates the barn with the ID of 11 DELETE /barns/11 Deletes the barn with the ID of 11 C R U D
  • 7. Some Good Ideas to Follow: 1. ALWAYS use plural nouns - keeps it simple 2. Nest resources! /barns/30/animals /barns/30/stables/1/animals 3. Handle errors with a standardized response body 4. Use the standard HTTP verbs 5. Use appropriate HTTP headers 6. Use appropriate HTTP response codes
  • 8. Read The Spec Status Codes: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html Headers: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
  • 9. Status Codes In a Nutshell ● 2xx - It worked ● 3xx - Go away ● 4xx - The client messed up ● 5xx - The server messed up
  • 10. Idempotent/Safe Methods Idempotent methods can be applied over and over again and always have the same effect on the resource Safe methods do not have any modifying effect on the resource
  • 11. Idempotent/Safe Methods Method Idempotent Safe GET YES YES POST NO NO PUT YES NO DELETE YES NO PATCH NO NO HEAD YES YES OPTIONS YES YES
  • 12. POST v PUT v PATCH ● POST is used to create an entity ● PUT is used to update an entity where you must send the entire representation of the entity as you wish for it to be stored ● PATCH is used to update an entity where you send only the fields that need updated
  • 13. CRUDy Workflow Client Application Server Client uses HTTP POST, GET, PUT and DELETE Verbs to CREATE, READ, UPDATE and DELETE
  • 14. Create an Animal $.post({ url: '/api/animals, data: { name: 'Bob', } }); Server returns “201 created” status and a JSON representation of the newly created street, as well a link to the street { id: 30, name: 'Bob', _links: { self: '/api/animals/30' } }
  • 15. Read Animals $.get({ url: '/api/animals, }); Server returns “200 OK”, and a JSON representation of the streets { page: 1, total_pages: 10, items: [ {id: 30, 'name': 'Bob', _links: { self: '/api/animals/30' }, .... ] }
  • 16. Update an Animal $.put({ url: '/api/animals/30', data: { name: 'Robert' } }); Server returns “200 OK” status and a JSON representation of the street, { id: 30, name: 'Robert', _links: { self: '/api/animals/30' } } NOTE: Most implementations of the PUT verb require the entire representation of the entity. See HTTP PATCH verb for updating with a partial representation of the entity.
  • 17. Delete an Animal $.ajax({ type: 'DELETE', url: '/api/animals/30' }); Server returns a ‘204 No Content’ status and should not have a response body. Any further GET requests to /api/animals/30 should return a ‘404 Not Found’ status
  • 18. Awesome! ● We can create some really awesome APIs where we can create, read, update, and delete entities in a standard way. ● These standards have lead to some very powerful libraries that can help you create and consume CRUD APIs
  • 19. Where is the Business Logic? Client Application Server Client uses HTTP POST, GET, PUT and DELETE Verbs to CREATE, READ, UPDATE and DELETE ● Sometimes this is what we want ● When we create APIs we don’t always know the specific use case ● We just want to expose the data
  • 20. Business Logic on The Client Side? ● A CRUD API is a really good way to expose meaningful data in a flexible way ● You make few assumptions on how the data will be displayed or used ● Fosters innovation and allows for really interesting clients
  • 21. Really? Client Side? ● Stopping at CRUD functionality limits what your API can actually do ● Complex business problems should not rely on client side implementations ● Only implementing CRUD functionality can lead to an API that doesn't know what it does, it only knows about the data it stores
  • 22. Wait, This SUCKS! How do you go beyond simply creating, reading, updating, and deleting things? ● How do you reroof a barn? ● Clean a stable? ● Castrate a goat?
  • 23. Commanding API Take a resources, add a command (verb) to the end, send data for that command in POST HTTP verb ○ POST /barns/11/reroof ○ POST /barns/1/stable/2/clean ○ POST /goats/133/castrate
  • 24. Command or Resource? Command Resource Verb Noun You can only POST and sometimes GET never PUT or DELETE All HTTP verbs are OK Once a command has been submitted, it cannot be removed or updated (read only) Most resources can be removed or updated
  • 25. HTTP Verb Command URL Explained POST /barns/11/reroof Sends the command to reroof barn 11 GET /barns/11/reroof Meta data about reroof command and barn 11. Maybe the last time it was reroofed, whether or not we are currently reroofing GET /barns/11/reroof/{cmdID} Meta data about the specific instance of the reroof command
  • 26. Commands Are NOT First Class Citizens POST /createBarn POST /barns POST /updateBarn PUT /barns/1 POST /cleanBarn POST /barns/1/clean
  • 27. Example: Reroof a barn $.post({ url: '/barns/11/reroof' }); Server responds with ‘200 OK’ status, and meta data about the command: {cmd_id: '123e4567-e89b-12d3-a456-426655440000'} In this example, the command is executed and completed within the lifecycle of the HTTP request.
  • 28. Wait: That’s Not The Whole Story We use a Commanding Pattern because we are performing an action on a resource. In the real word, these actions can take time.
  • 29. Reroof a Barn $.post({ url: '/barns/11/reroof' }); Server responds with ‘202 Accepted’ status, and meta data about the command: { cmd_id: '123e4567-e89b-12d3-a456-426655440000', _links: { status: '/barns/11/reroof/123e4567-e89b-12d3-a456-426655440000' } }
  • 30. Reroof a Barn; Check Status $.get({ url: '/barns/11/reroof/123e4567-e89b-12d3-a456-426655440000' }); Server responds with ‘200 OK’ status and data about the command { shingles_complete: 5, out_of: 1024, }
  • 31. Client Application Server Client sends POST command Clients Checks Status URL until complete, updating UI with progress
  • 32. What About Querying? ● Sometimes a query request cannot be completed in a reasonable amount of time ● Sometimes you have to send a POST payload in order to send enough data for the server to process a query ● This is a special case of a command
  • 33. Querying $.post({ url: '/chickens/search' data: { type: 'heritage' egg_color: 'blue', age: 'young' } }); Just like a command, we return ‘202 Accepted’ status, and return some meta data: { cmd_id: '7ecba660-5032-11e4-916c-0800200c9a66', _links: { results: '/chickens/searchResults/7ecba660-5032-11e4-916c-0800200c9a66', status: '/chickens/search/7ecba660-5032-11e4-916c-0800200c9a66', } }
  • 34. Getting Results... If you try to hit the results link before the results are complete: ● the server will return the search results in whatever state it is available ● return a ‘203 Non-Authoritative Information’ ● a link to the status url ● and a Retry-After header Using this pattern, you can expire content and return the 203 status code to tell the client to refresh the content
  • 35. Getting Results... HTTP Request Do we have the resource? 203 With a Retry After Header And Status URL 200 OK Has the data expired or still being created? Check Status Status Is it done?
  • 36. Separating Command and Queries... Developing expressive and meaningful endpoints... Using nouns and verbs that reflect what your API actually does... Proudly Inspired by Others
  • 38. CQRS Martin Fowler CQRS stands for Command Query Responsibility Segregation. It's a pattern that I first heard described by Greg Young. At its heart is a simple notion that you can use a different model to update information than the model you use to read information. This simple notion leads to some profound consequences for the design of information systems. http://martinfowler.com/bliki/CQRS.html
  • 39. DDD Wikipedia Domain-driven design (DDD) is an approach to software development for complex needs by connecting the implementation to an evolving model. The premise of domain-driven design is the following: 1. Placing the project's primary focus on the core domain and domain logic. 2. Basing complex designs on a model of the domain. 3. Initiating a creative collaboration between technical and domain experts to iteratively refine a conceptual model that addresses particular domain problems. http://en.wikipedia.org/wiki/Domain-driven_design
  • 40. DDD and CQRS in My Own Words... ● Domain Driven Design is a philosophy and methodology in which your domain model should represent the business problems that your app is actually solving ● Command Query Responsibility Segregation is the strategy of separating commands from queries, as opposed to CRUD functionality which is represented in the same object. CQRS can help you follow the SOLID principle
  • 41. DDD - Know Your Role! ● Talk to stakeholders and domain experts ● Strive for a ubiquitous language ● Know the context in which your API endpoints will be used ● Use this knowledge to develop your endpoints
  • 42. CRUD API Commanding API Create a Product POST /products POST /products Update a Product PUT /products/{id} PUT /products/{id} Mark Product as Active PUT /products/{id} POST /products/{id}/activate Describe a Product PUT /products/{id} POST /products/{id}/describe Order a Product ???? POST /products/{id}/order Markdown a Product PUT /products/{id} POST /products/{id}/markdown Review a products POST /products/{id}/reviews POST /products/{id}/review Mark product as out of stock PUT /products/{id} POST /products/{id}/outOfStock CRUDy v Commandy
  • 43. CQRS and CRUD, Mutually Exclusive?
  • 44. Commands Are NOT First Class Citizens POST /createBarn POST /barns POST /updateBarn PUT /barns/1 POST /cleanBarn POST /barns/1/clean
  • 45. CQRS and CRUD Can Coexist PUT or PATCH is just an update command BUT: ● Be very selective with what is allowed to be updated ● It is not always appropriate to expose update functionality for a particular object or property ● If another command updates a property, updating that property directly probably shouldn’t be allowed DELETE is a special use case command too