The document is a comprehensive guide on building REST services using Spring, authored by Josh Long. It covers topics such as Spring framework features, RESTful principles, HTTP methods, status codes, content negotiation, and security measures. The guide emphasizes the importance of error handling, API versioning, and the role of HATEOAS in RESTful services.
Introduction to Josh Long and the Spring REST Stack. Details about Spring's components and Spring Boot capabilities.
Overview of Spring MVC architecture, testing REST services with Spring MVC, and error handling in REST APIs.
Core concepts of REST including motivations, architectural constraints, HTTP verbs, status codes, and content negotiation.
Hypermedia, the Richardson Maturity Model levels of REST compliance and its implications for API design.
Spring Data REST enables easier RESTful service creation leveraging Spring Data Repositories.
Overview of Spring MVC architecture, testing REST services with Spring MVC, and error handling in REST APIs.
Strategies for versioning REST APIs and managing changes to APIs effectively.
Overview of security techniques in Spring REST, including OAuth, SSL/TLS, and x-auth for secure communications.
Microservices architecture, Spring's support for embedded servers, and getting production-ready REST services with Spring.
Microservices architecture, Spring's support for embedded servers, and getting production-ready REST services with Spring.Further resources for learning about Spring REST, recommendations for deeper dives into specific topics.
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
ABOUT ME
About JoshLong (⻰龙之春)
Spring Developer Advocate, Pivotal
Jean Claude
van Damme!
Java mascot Duke
@starbuxman
josh@joshlong.com
slideshare.net/joshlong
github.com/joshlong
speakerdeck.com/joshlong
some thing’s I’ve authored...
3.
T H ES P R I N G R E S T S TA C K
Starting with Spring
4.
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
SPRING IO
XD
BOOT
GRAILS
Stream, Taps,Jobs
Bootable, Minimal, Ops-Ready
Full-stack, Web
INTEGRATION
BATCH
BIG DATA
WEB
Channels, Adapters,
Filters, Transformers
Jobs, Steps,
Readers, Writers
Ingestion, Export,
Orchestration, Hadoop
Controllers, REST,
WebSocket
DATA
RELATIONAL
NON-RELATIONAL
CORE
FRAMEWORK
SECURITY
GROOVY
REACTOR
5.
A NEW HOMEFOR SPRING
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
6.
A NEW HOMEFOR SPRING
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
MODEL VIEW CONTROLLER
stopme if
you’ve heard
this one before ...
incoming
requests
delegate
request
DispatcherServlet
model
delegate
rendering of
response
return
response
model
return
control
render
response
view
template
controller
INSTALLING SPRING MVC
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
WebApplicationInitializer~= Java web.xml
!
public class SampleWebApplicationInitializer implements WebApplicationInitializer {
!
public void onStartup(ServletContext sc) throws ServletException {
AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
ac.setServletContext(sc);
ac.scan( “a.package.full.of.services”, “a.package.full.of.controllers” );
!
sc.addServlet("spring", new DispatcherServlet(ac));
!
// register filters, other servlets, etc., to get Spring and Spring Boot working
}
}
18.
INSTALLING SPRING MVC
or,just fill out the form...
public class SimplerDispatcherServletInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer {
!
!
!
}
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{ ServiceConfiguration.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{ WebMvcConfiguration.class };
}
@Override
protected String[] getServletMappings() {
return new String[]{"/*"};
}
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
19.
INSTALLING SPRING MVC
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
or,just use Spring Boot and never worry about it
@ComponentScan
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer {
!
private static Class< Application> applicationClass = Application.class;
!
!
}
!
public static void main(String[] args) {
SpringApplication.run(applicationClass);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(applicationClass);
}
20.
A RICH SERVLETTOOLKIT
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
other niceties Spring’s web support provides:
HttpRequestHandlers supports remoting technologies : Caucho, HTTP Invoker, etc.
DelegatingFilterProxy javax.filter.Filter that delegates to a Spring-managed bean
HandlerInterceptor wraps requests to HttpRequestHandlers
ServletWrappingController lets you force requests to a servlet through the Spring Handler chain
WebApplicationContextUtils look up the current ApplicationContext given a ServletContext
HiddenHttpMethodFilter routes HTTP requests to the appropriate endpoint
MOTIVATIONS FOR REST
meanwhile,in the enterprise,
somebody is using SOAP
because it’s “SIMPLE”
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
23.
WHAT IS REST?
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
RESTis an architectural constraint based on HTTP 1.1,
and created as part of Roy Fielding’s doctoral
dissertation in 2000.
It embraces HTTP.
It’s a style, not a standard
http://en.wikipedia.org/wiki/Representational_state_transfer
STATUS CODES
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
200 OK- Everything worked
!
201 Created - Returns a Location header for new resource
!
202 Accepted - server has accepted the request, but it is not yet
complete. Status URI optionally conveyed in Location header
31.
STATUS CODES
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
400 BadRequest - Malformed Syntax. Retry with change.
!
401 Unauthorized - authentication is required
403 Forbidden - server has understood, but refuses request
404 Not Found - server can’t find a resource for URI
406 Incompatible - incompatible Accept headers specified
409 Conflict - resource conflicts with client request
THE MATURITY MODEL
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
TheRichardson Maturity Model
Level 0: swamp of POX
Uses HTTP mainly as a tunnel through one URI
e.g., SOAP, XML-RPC
Usually features on HTTP verb (POST)
http://martinfowler.com/articles/richardsonMaturityModel.html
41.
THE MATURITY MODEL
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
TheRichardson Maturity Model
Level 1: resources
Multiple URIs to distinguish related nouns
e.g., /articles/1, /articles/2, vs. just /articles
http://martinfowler.com/articles/richardsonMaturityModel.html
42.
THE MATURITY MODEL
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
TheRichardson Maturity Model
Level 2: HTTP verbs
leverage transport-native properties to enhance service
e.g., HTTP GET and PUT and DELETE and POST
Uses idiomatic HTTP controls like status codes, headers
http://martinfowler.com/articles/richardsonMaturityModel.html
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
HATEOAS
The Richardson MaturityModel
Level 3: Hypermedia Controls (aka, HATEOAS)
No a priori knowledge of service required
Navigation options are provided by service and hypermedia controls
Promotes longevity through a uniform interface
http://martinfowler.com/articles/richardsonMaturityModel.html
45.
HATEOAS
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
Links provide possiblenavigations from a given resource
!
Links are dynamic, based on resource state.
!
<link href=“http://...:8080/users/232/customers”
rel= “customers”/>
!
{ href: “http://...:8080/users/232/customers”,
rel: “customers” }
SPRING DATA REST
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
SpringData REST simplifies the
generic data-centric @Controllers
!
Builds on top of Spring Data Repository support:
@RestResource (path = "users", rel = "users")
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
!
!
User findByUsername(@Param ("username") String username);
48.
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
SPRING DATA REST
SpringData REST simplifies the
generic data-centric @Controllers
!
Builds on top of Spring Data Repository support:
@RestResource (path = "users", rel = "users")
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
!
!
!
!
User findByUsername(@Param ("username") String username);
select u from User where u.username = ?
49.
SPRING DATA REST
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
SpringData REST simplifies the
generic data-centric @Controllers
!
Builds on top of Spring Data Repository support:
@RestResource (path = "users", rel = "users")
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
!
}
List<User> findUsersByFirstNameOrLastNameOrUsername(
@Param ("firstName") String firstName,
@Param ("lastName") String lastName,
@Param ("username") String username);
50.
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
SPRING DATA REST
SpringData REST simplifies the
generic data-centric @Controllers
!
Builds on top of Spring Data Repository support:
@RestResource (path = "users", rel = "users")
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
!
}
List<User> findUsersByFirstNameOrLastNameOrUsername(
@Param ("firstName") String firstName,
@Param ("lastName") String lastName,
@Param ("username") String username);
select u from User u
where u.username = ?
or u.firstName = ?
or u.lastName = ?
HANDLING ERRORS INA REST API
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
Developers learn to use an API through errors
Extreme programming and Test-Driven development
embrace this truth
!
Errors introduce transparency
55.
STATUS CODES
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
Status codesmap to errors
pick a meaningful subset of the
70+ status codes
200 - OK
201 - Created
304 - Created - Not Modified
400 - Bad Request
401 - Unauthorized
403 - Forbidden
404 - Not Found
500 - Internal Server Error
https://blog.apigee.com/detail/restful_api_design_what_about_errors
56.
DESCRIPTIVE ERRORS
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
Send meaningfulerrors along with status codes
{
"message": "authentication failed",
"errors": [
{
"resource": "Issue",
"field": "title",
"code": "missing_field"
}
]
}
{
"type": "authentication",
"message": “the username and
password provided are invalid” ,
"status": “401”
}
https://blog.apigee.com/detail/restful_api_design_what_about_errors
SPRING SECURITY
Security ishard. Don’t reinvent
the wheel!
!
Things to worry about when developing
web applications? EVERYTHING
!
(cross-site scripting, session fixation, identification,
authorization, and authentication, encryption, and SO
much more.)
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
64.
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
SPRING SECURITY
Spring Securityis a modern security
framework for a modern age
!
Yes
client submits
authentication
credentials
Authentication
Mechanism
collects the details
No - retry!
Authentication is
valid?
Store Authentication in
SecurityContextHolder
process original request
65.
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
SPRING SECURITY
Spring Securityis a modern security
framework for a modern age
!
Yes
client submits
authentication
credentials
Authentication
Mechanism
collects the details
Authentication
Store Authentication in
SecurityContextHolder
Authentication is
valid?
Mechanism collects the details!
!
No AuthenticationRequest is sent to AuthenticationManager!
- retry!
!
(passes it through a chain of AuthenticationProviders)!
!
AuthenticationProvider asks a UserDetailsService for a UserDetails!
!
The UserDetails object is used to build an Authentication object!
!
!
process original request
SECURING REST SERVICES
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
Usernamesand Passwords
!
If you can trust the client to keep a secret like a password, then it
can send the password using:
...HTTP Basic - passwords are sent plaintext!
... HTTP Digest - hashed passwords, but still plaintext.
SSL/TLS encryption helps prevent man-in-the-middle attacks
SSL AND TLS
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
SSL/TLSis used routinely to verify the identify of servers.
!
Normally, the client confirms the server, but the server rarely requires the
client to transmit a certificate.
!
It’s easy enough to setup SSL/TLS on your web server.
!
SSL AND TLS
SSL/TLScan be used to
identify the client to the server,
through mutual authentication.
!
!
browser/client must send their
certificate, as well.
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
@Override
protected void configure(HttpSecurity http)
throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.x509();
}
THE TROUBLE WITHPASSWORDS
Tim Bray says: Passwords don’t scale
!
Too easy to compromise.
!
Updating all your clients whenever you change
your password would be a nightmare!
!
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
75.
THE TROUBLE WITHPASSWORDS
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
OAUTH
OAuth is away for one (automated) process to securely
identify itself to another
!
Assumes a user context:
!
!
“I authorize $CLIENTX to act on $USER_Y’s behalf”
OAuth is a way of authorizing a client with particular access (scopes)
!
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
MICRO SERVICE ARCHITECTURE
MicroServices ...
!
Promote single responsibility principle
!
*
Promote loosely coupled, focused services.
!
(SOLID at the architecture level)
Don’t like it? Throw it away!
*
In object-oriented programming, the single responsibility principle states that every class
should have a single responsibility, and that responsibility should be entirely encapsulated by the
class. All its services should be narrowly aligned with that responsibility.!
http://en.wikipedia.org/wiki/Single_responsibility_principle
93.
EMBEDDED WEB SERVERS
SpringBoot supports Apache Tomcat 7 by default.
!
Easy to switch to Jetty, or Tomcat 8
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
NEXT STEPS
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
Spring IOGuides
http://spring.io/guides
!
Roy Fielding’s Dissertation introduces REST
http://www.ics.uci.edu/~fielding/pubs/dissertation/evaluation.htm#sec_6_1%7C
!
The Spring REST Shell
http://github.com/jbrisbin/rest-shell
!
Spring Security, Security OAuth, Spring Data REST, HATEOAS, Social
http://github.com/spring-projects
!
Spring MVC Test Framework
http://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/testing.html
!
102.
NEXT STEPS
GITHUB.COM/JOSHLONG/THE-SPRING-REST-STACK
Oliver Gierke’stalk on Hypermedia from Øredev
@ http://vimeo.com/53214577
Lez Hazelwood’s talk on designing a beautiful JSON+REST API
Ben Hale’s talk on REST API design with Spring from SpringOne2GX 2012
@ http://www.youtube.com/watch?v=wylViAqNiRA
My links:
github.com/joshlong/the-spring-rest-stack
slideshare.net/joshlong/rest-apis-with-spring
@starbuxman
!