SlideShare une entreprise Scribd logo
1  sur  27
Télécharger pour lire hors ligne
REST with Spring
    BJUG 6 @IBM

            Eugen Paraschiv
Overview
● Why REST?

● RESTful Constraints and Guidelines

● REST via Spring MVC

● Persistence with Spring Data

● Testing of a RESTful Service

● Q&A
Why REST
● REST is a set of Constraints (it's not the only
  one)
● Minimize Coupling between Client and
  Server
● Update the Server frequently without
  updating the Clients (no control over them)
● Support for many different types of Clients
● Scaling becomes easy(er)
The Four Levels of HTTP APIs - I, II
Level I. SOAP (Flickr SOAP API, Google AdSense API)
- WSDL describes the interface at design time
- no Resources are identified by URI - only Service Endpoints
- no difference between Resource and Representation
- HTTP treated as transport - no use of HTTP semantics


Level II. RPC (Amazon SimpleDB, Flickr 'REST' API)
+ the API exposes Resources (often corresponding to the application models)
- operations are done via actions in the URIs - the URI space is known at
design time (ex. /post/make_new)
- operations, failure codes are application specific
- HTTP treated as transport - no use of HTTP semantics
The Four Levels of HTTP APIs - III
Level III. HTTP (Twitter API)
+ Resources are exposed and identified by URIs
+ Resources are manipulated via Representations
+ HTTP semantics used correctly, use of generic media types (e.g.
application/xml)
- message semantics only known to Client and Server but not intermediaries -
Client and Server are coupled by original design
- application state machine is known at design time - assumptions about
available representations and transitions are hard-coded
The Four Levels of HTTP APIs - IV
Level IV. REST (Atom Pub, OpenSearch)
+ service description comes in the form of media type (and link relations)
specifications
+ Client only knows entry bookmark (the Root URI) and media types and no
specifics about the particular service
+ Client proceeds through application by looking at one response at a time,
each time evaluating how best to proceed given its overall goal and the
available transitions
+ Methods to use are known from media type (and link relations) specifications
or selected at runtime based on forms (form semantics known from media type
specifications)
REST SEC project
WHERE
- @github - https://github.com/eugenp/REST


WHY
- Reference Spring implementation of a REST Service
- Identity Management Solution as a Service


HOW
- REST/web: Spring 3.1.x
- Marshalling: Jackson 2.x (for JSON) and XStream (for XML)
- Persistence: Spring Data JPA and Hibernate 4.1.x
- Testing: Junit, Hamcrest, Mockito, rest-assured, RestTemplate (Apache
HTTP Client)
RESTful Constraints - I. Stateless
"Each request from client to server must contain all of the information
necessary to understand the request, and cannot take advantage of any stored
context on the server. Session state is therefore kept entirely on the client"



In Short
- no sessions, no cookies
- each request should contain it's authentication credentials

With Spring Security
<http create-session="stateless" ... >
RESTful Constraints - II. Cache
● Caching is on the Client side
● Goal of Client side Caching - partially or
  completely eliminate interactions with the
  Server
● HTTP Caching options:
  ● ETag/If-None-Match
  ● Last-Modified/If-Modified-Since
III. Caching - ETag - example
- ex: first, retrieve a Privilege resource:

curl -H "Accept: application/json" -i http://localhost:
8080/rest-sec/api/privileges/1

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Link: <http://localhost:8080/rest-sec/api/privileges>;
rel="collection"
ETag: "f88dd058fe004909615a64f01be66a7"
Last-Modified: Fri, 05 Oct 2012 11:36:33 GMT
Content-Type: application/json;charset=UTF-8
Content-Length: 52
Date: Fri, 05 Oct 2012 11:36:33 GMT
III. Caching - ETags - example (cont)
- next, use the etag value from the previous response to
retrieve the Privilege resource again:
curl -H "Accept: application/json" -H 'If-None-Match:
"f88dd058fe004909615a64f01be66a7"' -i http://localhost:
8080/rest-sec/api/privileges/1

HTTP/1.1 304 Not Modified
Server: Apache-Coyote/1.1
Link: <http://localhost:8080/rest-sec/api/privileges>;
rel="collection"
ETag: "f88dd058fe004909615a64f01be66a7"
Date: Fri, 05 Oct 2012 11:37:55 GMT
REST Constraint - III. Uniform
Interface
Uniform Interface Constraints
1. Identification of Resources
2. Manipulation of Resources through Representations
3. Self-descriptive Messages
4. Hypermedia As The Engine Of Application State
(HATEOAS)
III.1. Identification of Resources -
Spring MVC
For a sample foo resource:
- the Controller
@Controller
@RequestMapping(value = "foos")
public class FooController{ ... }



- retrieve by id: GET api/foos/id
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Foo findOne(@PathVariable("id") Long id){...}



- search: GET api/foos?q=query
@RequestMapping(params = {"q"}, method = RequestMethod.GET)
public List<Foo> search(@RequestParam("q") String query){...}
III.1. Identification of Resources -
Spring MVC (cont)
- create single (update the collection): POST api/foos
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void create(@RequestBody Foo resource) {...}



- update/override PUT api/foos/id
@RequestMapping(method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)
public void update(@RequestBody Foo resource) { ... }



- delete: DELETE api/foos/id
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable("id") Long id) { ... }
REST Constraint - III. Uniform
Interface
Supported Representations:
- JSON - application/json
- XML - application/xml
- future: ATOM

All read operations will perform Content
Negotiation when the Accept header is set on
the request
All write operations supports the Content-Type
header to be set on the request
Spring MVC - the Controller/Web
Layer
Simple Responsibilities:
- mapping of URIs
- Marshalling/Unmarshalling of Resource
Representations (implicit)
- Translation of Exceptions to HTTP Status
Codes
REST Constraint - III. Uniform
Interface - HATEOAS
- Discoverability at the root
- the Create operation
- making use of `rel`
- Advanced Topics: custom Mime Types, HAL
Persistence Layer - Spring Data
- DAO only with interfaces - no implementations
public interface IUserJpaDAO extends JpaRepository<User,
Long> { … }


- define a new, simple method:
List<User> findByLastname(String lastname);
List<User> findByEmailAddressAndLastname(String
emailAddress, String lastname);


- flexibility to use @Query
@Query("select u from User u where u.emailAddress = ?1")
User findByEmailAddress(String emailAddress);
Persistence Layer - Spring Data

● Pagination
Page<User> findByFirstname(String firstname, Pageable
pageable);



● Sorting
List<User> findByLastname(String lastname, Sort sort);
Persistence Layer - Spring Data
Other out of the box features - support for:
● Audit: create date, created by, last update date, last
   updated by
● Advanced Persistence APIs: QueryDSL,
   JPA 2 Specifications
Transactional Semantics
- the API Layer Strategy
● the Controller layer is the transactional
    owner
● the Service layer contains no transactional
    semantics
● there are no self-invocations or inter-
    invocations in the Controller layer - each
    invocation is a client call
Testing of a REST Service
● Live Tests: testing the deployed RESTful
    service
    ○ each RESTful service has a corresponding
        production API and a testing API
    ○ high level testing is done via the production API
    ○ lower level testing is done via the testing API
●   Integration tests: business, persistence

●   Unit tests
Testing - High Level Live Test (over
REST)
@Test
public void
givenResourceExists_whenResourceIsRetrievedByName_thenResourceIsFound() {
    // Given
    T existingResource = api.create(createNewEntity());

    // When
    T resourceByName = api.findByName(existingResource.getName());

    // Then
    assertNotNull(resourceByName);
}
Testing - Low Level Live Test (over
REST)
@Test
public void
givenInvalidResource_whenResourceIsUpdated_then409ConflictIsReceived() {
    // Given
    User existingUser = RestAssured.given().auth().preemptive().basic
(username, password).contentType("application/json").body(resourceAsJson).
post(uri).as(User.class);
    existingUser.setName(null);

    // When
    Response updateResponse = RestAssured.given().auth().preemptive().
basic(username, password).contentType("application/json").body
(existingUser).put(uri);

    // Then
    assertThat(updateResponse.getStatusCode(), is(409));
}
Security Concerns
- Basic and Digest Authentication with Spring
Security ON THE SAME URI (similar to
Content Negotiation):
● Authorization: Basic ...
● Authorization: Digest ...
Conclusion
Questions:
-?
-?
-?
-?
THANKS

Contenu connexe

Tendances

Dropwizard Spring - the perfect Java REST server stack
Dropwizard Spring - the perfect Java REST server stackDropwizard Spring - the perfect Java REST server stack
Dropwizard Spring - the perfect Java REST server stackJacek Furmankiewicz
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with SpringJoshua Long
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot IntroductionJeevesh Pandey
 
Building Beautiful REST APIs with ASP.NET Core
Building Beautiful REST APIs with ASP.NET CoreBuilding Beautiful REST APIs with ASP.NET Core
Building Beautiful REST APIs with ASP.NET CoreStormpath
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring BootTrey Howard
 
The Past Year in Spring for Apache Geode
The Past Year in Spring for Apache GeodeThe Past Year in Spring for Apache Geode
The Past Year in Spring for Apache GeodeVMware Tanzu
 
REST Easy with AngularJS - ng-grid CRUD EXAMPLE
REST Easy with AngularJS - ng-grid CRUD EXAMPLEREST Easy with AngularJS - ng-grid CRUD EXAMPLE
REST Easy with AngularJS - ng-grid CRUD EXAMPLEreneechemel
 
Spring Boot & WebSocket
Spring Boot & WebSocketSpring Boot & WebSocket
Spring Boot & WebSocketMing-Ying Wu
 
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
 
Content-centric architectures - case study : Apache Sling
Content-centric architectures - case study : Apache SlingContent-centric architectures - case study : Apache Sling
Content-centric architectures - case study : Apache SlingFabrice Hong
 
The never-ending REST API design debate
The never-ending REST API design debateThe never-ending REST API design debate
The never-ending REST API design debateRestlet
 
Lecture 7 Web Services JAX-WS & JAX-RS
Lecture 7   Web Services JAX-WS & JAX-RSLecture 7   Web Services JAX-WS & JAX-RS
Lecture 7 Web Services JAX-WS & JAX-RSFahad Golra
 
Using Java to implement SOAP Web Services: JAX-WS
Using Java to implement SOAP Web Services: JAX-WS�Using Java to implement SOAP Web Services: JAX-WS�
Using Java to implement SOAP Web Services: JAX-WSKatrien Verbert
 
WSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected Business
WSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected BusinessWSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected Business
WSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected BusinessWSO2
 

Tendances (19)

Dropwizard Spring - the perfect Java REST server stack
Dropwizard Spring - the perfect Java REST server stackDropwizard Spring - the perfect Java REST server stack
Dropwizard Spring - the perfect Java REST server stack
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with Spring
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Building Beautiful REST APIs with ASP.NET Core
Building Beautiful REST APIs with ASP.NET CoreBuilding Beautiful REST APIs with ASP.NET Core
Building Beautiful REST APIs with ASP.NET Core
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Android and REST
Android and RESTAndroid and REST
Android and REST
 
The Past Year in Spring for Apache Geode
The Past Year in Spring for Apache GeodeThe Past Year in Spring for Apache Geode
The Past Year in Spring for Apache Geode
 
JavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
JavaCro'14 - Building interactive web applications with Vaadin – Peter LehtoJavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
JavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
 
REST Easy with AngularJS - ng-grid CRUD EXAMPLE
REST Easy with AngularJS - ng-grid CRUD EXAMPLEREST Easy with AngularJS - ng-grid CRUD EXAMPLE
REST Easy with AngularJS - ng-grid CRUD EXAMPLE
 
Spring Boot & WebSocket
Spring Boot & WebSocketSpring Boot & WebSocket
Spring Boot & WebSocket
 
Spring 4 Web App
Spring 4 Web AppSpring 4 Web App
Spring 4 Web App
 
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.
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Content-centric architectures - case study : Apache Sling
Content-centric architectures - case study : Apache SlingContent-centric architectures - case study : Apache Sling
Content-centric architectures - case study : Apache Sling
 
The never-ending REST API design debate
The never-ending REST API design debateThe never-ending REST API design debate
The never-ending REST API design debate
 
Lecture 7 Web Services JAX-WS & JAX-RS
Lecture 7   Web Services JAX-WS & JAX-RSLecture 7   Web Services JAX-WS & JAX-RS
Lecture 7 Web Services JAX-WS & JAX-RS
 
Using Java to implement SOAP Web Services: JAX-WS
Using Java to implement SOAP Web Services: JAX-WS�Using Java to implement SOAP Web Services: JAX-WS�
Using Java to implement SOAP Web Services: JAX-WS
 
Angularjs & REST
Angularjs & RESTAngularjs & REST
Angularjs & REST
 
WSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected Business
WSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected BusinessWSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected Business
WSO2Con Asia 2014 - WSO2 AppDev Platform for the Connected Business
 

Similaire à Rest with Spring

ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiTiago Knoch
 
Networked APIs with swift
Networked APIs with swiftNetworked APIs with swift
Networked APIs with swiftTim Burks
 
Service approach for development Rest API in Symfony2
Service approach for development Rest API in Symfony2Service approach for development Rest API in Symfony2
Service approach for development Rest API in Symfony2Sumy PHP User Grpoup
 
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 CodeigniterSachin G Kulkarni
 
Xamarin Workshop Noob to Master – Week 5
Xamarin Workshop Noob to Master – Week 5Xamarin Workshop Noob to Master – Week 5
Xamarin Workshop Noob to Master – Week 5Charlin Agramonte
 
Restful web services rule financial
Restful web services   rule financialRestful web services   rule financial
Restful web services rule financialRule_Financial
 
RESTful API-centric Universe
RESTful API-centric UniverseRESTful API-centric Universe
RESTful API-centric UniverseTihomir Opačić
 
nguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-servicenguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-servicehazzaz
 
Design Summit - RESTful API Overview - John Hardy
Design Summit - RESTful API Overview - John HardyDesign Summit - RESTful API Overview - John Hardy
Design Summit - RESTful API Overview - John HardyManageIQ
 
Embrace HTTP with ASP.NET Web API
Embrace HTTP with ASP.NET Web APIEmbrace HTTP with ASP.NET Web API
Embrace HTTP with ASP.NET Web APIFilip W
 
Rest api titouan benoit
Rest api   titouan benoitRest api   titouan benoit
Rest api titouan benoitTitouan BENOIT
 
Cloud Side: REST APIs - Best practices
Cloud Side: REST APIs - Best practicesCloud Side: REST APIs - Best practices
Cloud Side: REST APIs - Best practicesNicolas FOATA
 
Building Restful Applications Using Php
Building Restful Applications Using PhpBuilding Restful Applications Using Php
Building Restful Applications Using PhpSudheer Satyanarayana
 

Similaire à Rest with Spring (20)

ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
 
APITalkMeetupSharable
APITalkMeetupSharableAPITalkMeetupSharable
APITalkMeetupSharable
 
Networked APIs with swift
Networked APIs with swiftNetworked APIs with swift
Networked APIs with swift
 
REST APIs
REST APIsREST APIs
REST APIs
 
Service approach for development Rest API in Symfony2
Service approach for development Rest API in Symfony2Service approach for development Rest API in Symfony2
Service approach for development Rest API in Symfony2
 
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
 
Xamarin Workshop Noob to Master – Week 5
Xamarin Workshop Noob to Master – Week 5Xamarin Workshop Noob to Master – Week 5
Xamarin Workshop Noob to Master – Week 5
 
Restful web services rule financial
Restful web services   rule financialRestful web services   rule financial
Restful web services rule financial
 
RESTful API-centric Universe
RESTful API-centric UniverseRESTful API-centric Universe
RESTful API-centric Universe
 
nguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-servicenguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-service
 
Apitesting.pptx
Apitesting.pptxApitesting.pptx
Apitesting.pptx
 
ASP.NET WEB API Training
ASP.NET WEB API TrainingASP.NET WEB API Training
ASP.NET WEB API Training
 
Design Summit - RESTful API Overview - John Hardy
Design Summit - RESTful API Overview - John HardyDesign Summit - RESTful API Overview - John Hardy
Design Summit - RESTful API Overview - John Hardy
 
Embrace HTTP with ASP.NET Web API
Embrace HTTP with ASP.NET Web APIEmbrace HTTP with ASP.NET Web API
Embrace HTTP with ASP.NET Web API
 
Best Practices in Api Design
Best Practices in Api DesignBest Practices in Api Design
Best Practices in Api Design
 
Rest api titouan benoit
Rest api   titouan benoitRest api   titouan benoit
Rest api titouan benoit
 
Apex REST
Apex RESTApex REST
Apex REST
 
Web api
Web apiWeb api
Web api
 
Cloud Side: REST APIs - Best practices
Cloud Side: REST APIs - Best practicesCloud Side: REST APIs - Best practices
Cloud Side: REST APIs - Best practices
 
Building Restful Applications Using Php
Building Restful Applications Using PhpBuilding Restful Applications Using Php
Building Restful Applications Using Php
 

Dernier

HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 

Dernier (20)

HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

Rest with Spring

  • 1. REST with Spring BJUG 6 @IBM Eugen Paraschiv
  • 2. Overview ● Why REST? ● RESTful Constraints and Guidelines ● REST via Spring MVC ● Persistence with Spring Data ● Testing of a RESTful Service ● Q&A
  • 3. Why REST ● REST is a set of Constraints (it's not the only one) ● Minimize Coupling between Client and Server ● Update the Server frequently without updating the Clients (no control over them) ● Support for many different types of Clients ● Scaling becomes easy(er)
  • 4. The Four Levels of HTTP APIs - I, II Level I. SOAP (Flickr SOAP API, Google AdSense API) - WSDL describes the interface at design time - no Resources are identified by URI - only Service Endpoints - no difference between Resource and Representation - HTTP treated as transport - no use of HTTP semantics Level II. RPC (Amazon SimpleDB, Flickr 'REST' API) + the API exposes Resources (often corresponding to the application models) - operations are done via actions in the URIs - the URI space is known at design time (ex. /post/make_new) - operations, failure codes are application specific - HTTP treated as transport - no use of HTTP semantics
  • 5. The Four Levels of HTTP APIs - III Level III. HTTP (Twitter API) + Resources are exposed and identified by URIs + Resources are manipulated via Representations + HTTP semantics used correctly, use of generic media types (e.g. application/xml) - message semantics only known to Client and Server but not intermediaries - Client and Server are coupled by original design - application state machine is known at design time - assumptions about available representations and transitions are hard-coded
  • 6. The Four Levels of HTTP APIs - IV Level IV. REST (Atom Pub, OpenSearch) + service description comes in the form of media type (and link relations) specifications + Client only knows entry bookmark (the Root URI) and media types and no specifics about the particular service + Client proceeds through application by looking at one response at a time, each time evaluating how best to proceed given its overall goal and the available transitions + Methods to use are known from media type (and link relations) specifications or selected at runtime based on forms (form semantics known from media type specifications)
  • 7. REST SEC project WHERE - @github - https://github.com/eugenp/REST WHY - Reference Spring implementation of a REST Service - Identity Management Solution as a Service HOW - REST/web: Spring 3.1.x - Marshalling: Jackson 2.x (for JSON) and XStream (for XML) - Persistence: Spring Data JPA and Hibernate 4.1.x - Testing: Junit, Hamcrest, Mockito, rest-assured, RestTemplate (Apache HTTP Client)
  • 8. RESTful Constraints - I. Stateless "Each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client" In Short - no sessions, no cookies - each request should contain it's authentication credentials With Spring Security <http create-session="stateless" ... >
  • 9. RESTful Constraints - II. Cache ● Caching is on the Client side ● Goal of Client side Caching - partially or completely eliminate interactions with the Server ● HTTP Caching options: ● ETag/If-None-Match ● Last-Modified/If-Modified-Since
  • 10. III. Caching - ETag - example - ex: first, retrieve a Privilege resource: curl -H "Accept: application/json" -i http://localhost: 8080/rest-sec/api/privileges/1 HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Link: <http://localhost:8080/rest-sec/api/privileges>; rel="collection" ETag: "f88dd058fe004909615a64f01be66a7" Last-Modified: Fri, 05 Oct 2012 11:36:33 GMT Content-Type: application/json;charset=UTF-8 Content-Length: 52 Date: Fri, 05 Oct 2012 11:36:33 GMT
  • 11. III. Caching - ETags - example (cont) - next, use the etag value from the previous response to retrieve the Privilege resource again: curl -H "Accept: application/json" -H 'If-None-Match: "f88dd058fe004909615a64f01be66a7"' -i http://localhost: 8080/rest-sec/api/privileges/1 HTTP/1.1 304 Not Modified Server: Apache-Coyote/1.1 Link: <http://localhost:8080/rest-sec/api/privileges>; rel="collection" ETag: "f88dd058fe004909615a64f01be66a7" Date: Fri, 05 Oct 2012 11:37:55 GMT
  • 12. REST Constraint - III. Uniform Interface Uniform Interface Constraints 1. Identification of Resources 2. Manipulation of Resources through Representations 3. Self-descriptive Messages 4. Hypermedia As The Engine Of Application State (HATEOAS)
  • 13. III.1. Identification of Resources - Spring MVC For a sample foo resource: - the Controller @Controller @RequestMapping(value = "foos") public class FooController{ ... } - retrieve by id: GET api/foos/id @RequestMapping(value = "/{id}", method = RequestMethod.GET) public Foo findOne(@PathVariable("id") Long id){...} - search: GET api/foos?q=query @RequestMapping(params = {"q"}, method = RequestMethod.GET) public List<Foo> search(@RequestParam("q") String query){...}
  • 14. III.1. Identification of Resources - Spring MVC (cont) - create single (update the collection): POST api/foos @RequestMapping(method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public void create(@RequestBody Foo resource) {...} - update/override PUT api/foos/id @RequestMapping(method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) public void update(@RequestBody Foo resource) { ... } - delete: DELETE api/foos/id @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.NO_CONTENT) public void delete(@PathVariable("id") Long id) { ... }
  • 15. REST Constraint - III. Uniform Interface Supported Representations: - JSON - application/json - XML - application/xml - future: ATOM All read operations will perform Content Negotiation when the Accept header is set on the request All write operations supports the Content-Type header to be set on the request
  • 16. Spring MVC - the Controller/Web Layer Simple Responsibilities: - mapping of URIs - Marshalling/Unmarshalling of Resource Representations (implicit) - Translation of Exceptions to HTTP Status Codes
  • 17. REST Constraint - III. Uniform Interface - HATEOAS - Discoverability at the root - the Create operation - making use of `rel` - Advanced Topics: custom Mime Types, HAL
  • 18. Persistence Layer - Spring Data - DAO only with interfaces - no implementations public interface IUserJpaDAO extends JpaRepository<User, Long> { … } - define a new, simple method: List<User> findByLastname(String lastname); List<User> findByEmailAddressAndLastname(String emailAddress, String lastname); - flexibility to use @Query @Query("select u from User u where u.emailAddress = ?1") User findByEmailAddress(String emailAddress);
  • 19. Persistence Layer - Spring Data ● Pagination Page<User> findByFirstname(String firstname, Pageable pageable); ● Sorting List<User> findByLastname(String lastname, Sort sort);
  • 20. Persistence Layer - Spring Data Other out of the box features - support for: ● Audit: create date, created by, last update date, last updated by ● Advanced Persistence APIs: QueryDSL, JPA 2 Specifications
  • 21. Transactional Semantics - the API Layer Strategy ● the Controller layer is the transactional owner ● the Service layer contains no transactional semantics ● there are no self-invocations or inter- invocations in the Controller layer - each invocation is a client call
  • 22. Testing of a REST Service ● Live Tests: testing the deployed RESTful service ○ each RESTful service has a corresponding production API and a testing API ○ high level testing is done via the production API ○ lower level testing is done via the testing API ● Integration tests: business, persistence ● Unit tests
  • 23. Testing - High Level Live Test (over REST) @Test public void givenResourceExists_whenResourceIsRetrievedByName_thenResourceIsFound() { // Given T existingResource = api.create(createNewEntity()); // When T resourceByName = api.findByName(existingResource.getName()); // Then assertNotNull(resourceByName); }
  • 24. Testing - Low Level Live Test (over REST) @Test public void givenInvalidResource_whenResourceIsUpdated_then409ConflictIsReceived() { // Given User existingUser = RestAssured.given().auth().preemptive().basic (username, password).contentType("application/json").body(resourceAsJson). post(uri).as(User.class); existingUser.setName(null); // When Response updateResponse = RestAssured.given().auth().preemptive(). basic(username, password).contentType("application/json").body (existingUser).put(uri); // Then assertThat(updateResponse.getStatusCode(), is(409)); }
  • 25. Security Concerns - Basic and Digest Authentication with Spring Security ON THE SAME URI (similar to Content Negotiation): ● Authorization: Basic ... ● Authorization: Digest ...