0% found this document useful (0 votes)
11 views33 pages

Chapter 9 Service API and Contract Design With RS and Microservice - En

The document discusses the design considerations for service APIs and contracts, focusing on REST services and microservices. It outlines various service models, including entity, utility, microservice, and task service designs, along with guidelines for creating uniform contracts, methods, and media types. Additionally, it presents a case study on the MUA Confer Student Award service, detailing specific service contracts and design considerations for effective API implementation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views33 pages

Chapter 9 Service API and Contract Design With RS and Microservice - En

The document discusses the design considerations for service APIs and contracts, focusing on REST services and microservices. It outlines various service models, including entity, utility, microservice, and task service designs, along with guidelines for creating uniform contracts, methods, and media types. Additionally, it presents a case study on the MUA Confer Student Award service, detailing specific service contracts and design considerations for effective API implementation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Service API and Contract Design

with
REST Services and Microservices

[email protected]
1. Service Model Design Considerations
Entity Service Design
• REST Entity Services defines a • Example
functional boundary for business • Invoice entity service with two
entities standard HTTP methods and two
• Primarily handles data processing complex methods
related to the entity
• Uses idempotent HTTP methods
(GET, PUT, DELETE) for reliability
• Complex Methods (Optional): If
allowed by service inventory’s design
standards
Utility Service Design
• Utility Services • Example: HR System Utility
• Reusable & agnostic, but without a Service
fixed functional scope • Retrieves employee data from a
• Validate method-resource choices legacy HR system
before finalizing • Used by other services for employee
info
• Characteristics
• Flexible boundaries, often wrapping
legacy systems
• Provides read-only access to legacy
data
• SOA Patterns
• Dual Protocols
• Concurrent Contracts
• Service Façade
• Legacy Wrapper
Microservice Design
• Microservice • Example: Confirm Authorization
• Non-agnostic – Designed for specific • A microservice contract with a
business processes singlepurpose, non-agnostic
• Limited consumers – Often serves only functional scope
one service
• Flexibility in contract design –
Standardization is optional
• Challenges
• Ensuring performance & reliability and
runtime efficiency
• SOA & Microservice Patterns
• Microservice Deployment
• Containerization
• Service Data Replication
• Redundant Implementation
Task Service Design
• Task Service Design in REST • Example: Validate Timesheet Task
APIs Service
• Single-purpose – Often limited to one • Trigger
key function • Check Status
• Triggered by POST requests – • Cancel Task
Requires reliability measures
• Handling Asynchronous
Processes
• For long-running tasks
• State tracking capabilities – Using
additional service endpoints
• Cancellation support – Allows
stopping active processes
2. CASE STUDY EXAMPLE
MUA Confer Student Award
• The service modeling process
performed by MUA produced a
number of REST service
candidates

• Architects use these select service


candidates (modeled in Chapter 7)
as the basis for their service
contract designs.
MUA Confer Student Award Service Contract

• Student Award Application Process


• Students submit applications via a web form.
• Server processes form into an XML document:
application/vnd.edu.mua.student-
award-conferral-application+xhtml+xml
• Add new service capabilities: DELETE
and GET
• Design Considerations
• Data includes both human-readable & machine-
readable formats
• RESTful security ensures only authorized access to
sensitive data
Event Service Contract (Entity)
• Added additional capabilities for
broader reuse beyond the Confer
Student Award process
• Key Capabilities
• GET /event/{id} – Retrieves event
details
• GET /event/{id}/calendar – Fetches
event calendar details
• GET /event/{id}/description –
Provides a detailed event description
Award Service Contract (Entity)
• Uses code-on-demand approach
to execute logic within the Confer
Student Award Task Service
• GET /award/conferral-rules –
Provides award rules in two
formats
• Human-readable HTML (for
students)
• Javascript format (for integration
with the task service)
Student Transcript Service Contract (Entity)
• Why a Separate Student
Transcript Service?
• The original Student Service was too
broad and complex
• It was split into specialized entity
services, including the Student
Transcript Service
• Design Considerations
• The Confer Student Award process
only needs transcript data, not full
student details.
• The Student Transcript Service
replaces the Student Service in this
process
Notification & Document Service Contracts (Utility)

• Both handle human-readable data


(HTML/PDF) -> Why Separate
Notification & Document
Services?
• Notification Service → Manages
email notifications.
• Document Service → Manages
printed and postal document
delivery
• Confer Student Award process
• The task service selects the preferred
delivery method from the application
form.
• Uses POST request to send
notifications/documents
2. REST Service Design Guidelines
Uniform Contract & Methods
• Key Considerations for a Uniform • Designing and Standardizing
Contract Methods
• Balance features & limitations • Minimize methods but allow for
• Use web-centric technology as a expansion when necessary
foundation but customize when • HTTP provides fundamental
needed. methods: GET, PUT, DELETE, POST.
• Standardize methods, media types, • Less common methods like PATCH
and exception handling. can be used for partial updates
• Custom protocol, methods & headers
Designing and Standardizing HTTP Headers

• HTTP Headers in REST Services • Custom Headers & Must-


• Enhance message exchange by Understand Semantics
providing metadata. • Custom headers can extend
• Help service agents process messages functionality while maintaining
effectively. backward compatibility.
• Support service composition for • If services must understand a header,
automating business tasks. a new HTTP method may be required
• Some use case for Built-in HTTP
Headers
• Alternative to query strings • SOA Governance must ensure
• Response metadata consistency in custom headers
• General service/consumer info across the service inventory
Designing and Standardizing HTTP Response Codes

• The codes and reasons provided • But, HTTP does not define how
by HTTP are standardized consumers should react to codes
• HTTP Response Code Ranges & → needs standardization
Their Meaning • SOA projects must enforce
• 100-199 → Informational consistent response code
• 200-299 → Success handling
• 300-399 → Redirection
• 400-499 → Client Errors
• 500-599 → Server Errors
• Standardized HTTP response
codes ensure predictable, efficient
REST API behavior
Customizing Response Codes
• The HTTP specification allows • Guideline for Custom Response
for extensions to response codes Codes
• Custom codes should follow existing • Keep codes uniform
HTTP ranges • Make response messages human-
readable
• Ensure reusability
• Avoid code conflicts
• Introduce codes only when necessary

• Thoughtful customization
improves REST API clarity &
consistency while maintaining
compatibility!
Designing Media Types
• Importance of Media Types in • Guideline for Defining Media
Service Inventories Types
• Media types change more frequently • Use existing media types when
than methods possible
• Standard Web Media Types for • Media types should be schema-
specific
Service Inventories
• Keep them abstract
• text/plain; charset=utf-8
• Enable extensibility
• application/xhtml+xml
• Provide standard processing
• application/json instructions
• text/uri-list
• application/atom+xml
Designing Media Types (2)
• Custom Media Type Naming Convention
• Format: application/vnd.organization.type+supertype
• Example:
• application/vnd.com.examplebooks.purchase-order+xml
• application → Machine-readable format.
• vnd.com.examplebooks → Vendor namespace (examplebooks.com)
• purchase-order → Media type name.
• +xml → Derived from XML (compatible with XML parsers).

• Thoughtful media type design enhances compatibility,


extensibility, and machine readability in RESTful services.
Designing Schemas for Media Types
• Schemas define structured data • Guideline, flexibility is key
models for RESTful services. • Schema should allow broad
applicability across multiple services
• Common schema formats
• Coarse validation constraints enable
• XML Schema (XSD) → Used for adaptability
structured, hierarchical data.
• Avoid overly strict typing → Helps
• JSON Schema → More lightweight, with reusability
widely used in modern APIs.

• Schemas must be defined at the


uniform contract level → Service-
specific schemas violate REST
principles.
Complex Method Design
• Why Customize Beyond Basic • What Are Complex Methods?
HTTP Methods? • Extend basic HTTP methods with
• Service inventories are controlled additional rules
environments → Can enforce stricter • Designed for specific interactions
rules. where simple methods are insufficient
• Customization improves • Combine multiple functions into an
predictability & quality-of-service. aggregate interaction
• Example:
• Retrieving accounting documents
(invoices, orders): • Benefit: Standardized system
• Automatic retry on failure. with custom logic for critical
• State remains unchanged during operations.
retries.
Complex Method Design (2)
• Complex methods encapsulate multiple
primitive methods and additional logic
• Standardized within a service inventory
for consistency
• Common complex methods
• Fetch – Recovers from errors during multiple
GET requests
• Store – Ensures reliable PUT or DELETE
operations
• Delta – Keeps consumers updated on
changing resources
• Async – Supports asynchronous request
processing
• Helps reduce redundant logic and
simplifies maintenance
Stateless Complex Methods – Fetch Method

• Stateless means there is no


memory of the past
• Fetch Method enhances HTTP
GET for reliable data retrieval
• Automatic retries on timeout or
failure.
• Content negotiation ensures
compatibility
• Redirection handling supports
contract changes
• Cache control directives optimize
performance
Stateless Complex Methods – Store Method

• Store method enhances PUT and


DELETE for resource updates.
• Provides automatic retries, content
negotiation, and redirection
handling
• Ensures idempotency: repeating a
successful request has no additional
effect.
• Helps handle timeouts, low
bandwidth, and failed requests
efficiently.
Stateless Complex Methods – Delta Method

• Delta method keeps consumers


synchronized with resource state
changes.
• Mechanism
• Service maintains a history of
changes.
• Consumers retrieve only the updates
since their last query.
• Responses include links to the next
delta or indicate no changes

• Helps optimize bandwidth &


reduce redundant data retrieval.
Stateless Complex Methods – Async Method

• Async method handles long-


running requests without
requiring an open connection.
• Mechanism
• The consumer sends a request with a
callback URL.
• The service responds with 202
Accepted and may return a tracking
resource identifier.
• When processing completes, the
service sends the result to the
callback URL
• The consumer can send a DELETE
request to cancel an ongoing request
Stateful Complex Methods – Trans Method

• Trans method supports two-phase


commit transactions between
services
• Ensures all changes succeed or all are
rolled back.
• Introduces a custom PREP-PUT
method (prepares changes
without committing)
• Requires a transaction controller
for commit/rollback management
Stateful Complex Methods – PubSub Method

• PubSub method supports real-


time event-driven interactions
• Acts as a cache-invalidation
mechanism
• Service pushes notifications about
changes
• Consumers pull updates using Fetch.
• Minimizes state storage and
reduces redundant fetches
• Can distribute (/topic) load efficiently
in cloud environments
MUA Case study – OptLock Method
• Challenge: Concurrent updates to the
same resource cause conflicts
• Solution: Introduce OptLock
(Optimistic Locking) method.
• Mechanism
• Consumer fetches resource → Receives
ETag (version identifier).
• Consumer updates resource → Sends If-
Match header with ETag.
• If resource is unchanged, update is
accepted; otherwise, rejected (409
Conflict).
• Limitations:
• Works best for low write-frequency
resources.
• High concurrency can cause frequent
conflicts and retries.
Need for Pessimistic Locking (PesLock Method)

• Problem with OptLock


• Frequent 409 Conflict errors during peak usage.
• High concurrency makes retries inefficient
• Proposed Solution
• Switch to PesLock (Pessimistic Locking).
• PesLock ensures
• Exclusive access to a resource during updates
• Reduces conflict risk by preventing concurrent modifications.
MUA Case study – PesLock Method

• PesLock ensures exclusive access


but introduces stateful
interactions
• Limits concurrent access while the
lock is held
• Access control is required to prevent
unauthorized locks.
• Locks must have time out
• Considerations
• Start with OptLock for efficiency.
• If three retries fail, fallback to
PesLock for guaranteed execution.
Q&A

You might also like