0% found this document useful (0 votes)
8 views250 pages

CHAPTER 4D spring Exception

The document outlines the process of handling exceptions in a Spring REST application, specifically for cases where a student ID is not found. It details the steps to create a custom error response class, a custom exception class, and how to implement an exception handler method using the @ExceptionHandler annotation. The goal is to return error responses in JSON format instead of HTML error pages when exceptions occur.

Uploaded by

elatan72112
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views250 pages

CHAPTER 4D spring Exception

The document outlines the process of handling exceptions in a Spring REST application, specifically for cases where a student ID is not found. It details the steps to create a custom error response class, a custom exception class, and how to implement an exception handler method using the @ExceptionHandler annotation. The goal is to return error responses in JSON format instead of HTML error pages when exceptions occur.

Uploaded by

elatan72112
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 250

Spring REST - Exception

Handling

HiLCoE school of Computer science and technology


Remember our
problem?
Remember our
problem?
• Bad student id of
9999 …
Remember our
problem?
• Bad student id of
9999 …
Remember our Scary HTML
problem?
• Bad student id of
error page
9999 …
We really want
this …
We really want
this …
•Handle the exception and return error
as JSON
We really want
this …
•Handle the exception and return error
as JSON
Spring REST Exception
Handling
REST
Servi
ce
RES
T
Clie
nt
Spring REST Exception
Handling
REST
Servi
/api/students/9999
ce
RES
T
Clie
nt
Spring REST Exception
Handling
Bad REST
data
Servi
/api/students/9999
ce
RES
T
Clie
nt
Spring REST Exception
Handling
Bad REST
data
Servi
/api/students/9999
ce
RES T
T h
r
Clie o
nt w

e
x
c
e
p
Spring REST Exception
Handling
Bad REST
data
Servi
/api/students/9999
ce
RES T
T h
Excepti r
Clie on
o
Handle
nt r
w

e
x
c
e
p
Spring REST Exception
Handling
Bad REST
data
Servi
/api/students/9999
ce
RES T
T h
Excepti r
Clie on
o
Handle
nt r
w

e
x
c
e
p
Development Step-
By-St
ep

Process
Development Step-
By-St
ep

Process
1. Create a
custom error response
class

HiLCoE school of Computer science and technology


Development Step-
By-St
ep

Process
1. Create a custom error
response class

2. Create a custom exception


class
Development Step-
By-St
ep

Process
1. Create a custom error response class

2. Create a custom exception class

3. Update REST service to throw exception if student


not found
Development Step-
By-St
ep

Process
1. Create a custom error response class

2. Create a custom exception class

3. Update REST service to throw exception if student


not found

4. Add an exception handler method


using @ExceptionHandler
Step 1: Create custom error
response class
Step 1: Create custom error
response class
• The custom error response class will be sent back to
client as JSON
Step 1: Create custom error
response class
• The custom error response class will be sent back to
client as JSON

• We will define as Java class


(POJO)
Step 1: Create custom error
response class
• The custom error response class will be sent back to
client as JSON

• We will define as Java class


(POJO)

• Jackson will handle converting it to


JSON
Step 1: Create custom error
response class
• The custom error response class will be sent back to
client as JSON

• We will define as Java class You can define any


custom fields that
(POJO) you want to track

• Jackson will handle converting it to


JSON
Step 1: Create custom error
response class
Step 1: Create custom error
response class
File: StudentErrorResponse.java

public class StudentErrorResponse


{
private int status;
String message;
private long timeStamp;

private
Step 1: Create custom error
response class
File: StudentErrorResponse.java

public class StudentErrorResponse


{
private int status;
String message;
private long timeStamp;

private
// constructors

// getters / setters

}
Step 2: Create custom student
exception
Step 2: Create custom student
exception
• The custom student exception will used by our
REST service
Step 2: Create custom student
exception
• The custom student exception will used by our
REST service

• In our code, if we can't find student, then we'll throw an


exception
Step 2: Create custom student
exception
• The custom student exception will used by our
REST service

• In our code, if we can't find student, then we'll throw an


exception

• Need to define a custom student


exception class
Step 2: Create custom student
exception
• The custom student exception will used by our
REST service

• In our code, if we can't find student, then we'll throw an


exception

• Need to define a custom student


exception class
• StudentNotFoundException
Step 2: Create custom student
exception
Step 2: Create custom student
exception
File: StudentNotFoundException.java

public class StudentNotFoundExceptio extends RuntimeException {


n
Step 2: Create custom student
exception
File: StudentNotFoundException.java

public class extends RuntimeException {


StudentNotFoundException
public message) {
StudentNotFoundException(String
super(message);
}

}
Call super
class
constructo
r
Step 3: Update REST service to throw
exception
Step 3: Update REST service to throw
exception
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class
StudentRestController {
Step 3: Update REST service to throw
exception
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class
StudentRestController {
@GetMapping("/students/{studentId}")
public Student getStudent(@PathVariable int studentId) {
Step 3: Update REST service to throw
exception
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class
StudentRestController {
@GetMapping("/students/{studentId}")
public Student getStudent(@PathVariable int studentId) {

// check the studentId against list size

if ( (studentId >= theStudents.size()) || (studentId < 0) ) {


throw new StudentNotFoundException("Student id notfound - " + studentId);
}

Throw
exception
Step 3: Update REST service to throw
exception
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class Could also
StudentRestController {
@GetMapping("/students/{studentId}") check
public Student getStudent(@PathVariable int studentId) { results
// check the studentId against list size from DB
if ( (studentId >= theStudents.size()) || (studentId < 0) ) {
throw new StudentNotFoundException("Student id notfound - " + studentId);
}

Throw
exception
Step 3: Update REST service to throw
exception
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class
StudentRestController {
@GetMapping("/students/{studentId}")
public Student getStudent(@PathVariable int studentId) {

// check the studentId against list size

if ( (studentId >= theStudents.size()) || (studentId < 0) ) {


throw new StudentNotFoundException("Student id notfound - " + studentId);
}

return theStudents.get(studentId);

}
Throw
… exception
}
Happy
path
Spring REST Exception
Handling
REST
Servi
/api/students/9999
ce
RES
T
Clie
nt
Spring REST Exception
Handling
Bad REST
data
Servi
/api/students/9999
ce
RES
T
Clie
nt
Spring REST Exception
Handling
Bad REST
data
Servi
/api/students/9999
ce
RES T
T h
r
Clie o
nt w

e
x
c
e
p
Spring REST Exception
Handling
Bad REST
data
Servi
/api/students/9999
ce
RES T
T h
Excepti r
Clie on
o
Handle
nt r
w

e
x
c
e
p
Step 4: Add exception handler
method
Step 4: Add exception handler
method
• Define exception handler method(s) with @ExceptionHandler
annotation
Step 4: Add exception handler
method
• Define exception handler method(s) with @ExceptionHandler
annotation

• Exception handler will return a


ResponseEntity
Step 4: Add exception handler
method
• Define exception handler method(s) with @ExceptionHandler
annotation

• Exception handler will return a


ResponseEntity

• ResponseEntity is a wrapper for the HTTP response


object
Step 4: Add exception handler
method
• Define exception handler method(s) with @ExceptionHandler
annotation

• Exception handler will return a


ResponseEntity

• ResponseEntity is a wrapper for the HTTP response


object

• ResponseEntity provides fine-grained control to


specify:
Step 4: Add exception handler
method
• Define exception handler method(s) with @ExceptionHandler
annotation

• Exception handler will return a


ResponseEntity

• ResponseEntity is a wrapper for the HTTP response


object

• ResponseEntity provides fine-grained control to


specify:

• HTTP status code, HTTP headers and Response


body
Step 4: Add exception handler
method
Step 4: Add exception handler
method
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class
StudentRestController {

Step 4: Add exception handler
method
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class
StudentRestController {

@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(StudentNotFoundException exc) {
Step 4: Add exception handler
method
File: StudentRestController.java
Exception
@handler
RestC on t r o
m e t h
@RequestMapping("/api")
public class StudentRestController {
ol…dler
@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(StudentNotFoundException exc) {
Step 4: Add exception handler
method
File: StudentRestController.java
Exception
Type of
the
response
@handler
RestC on t r o
m e t h
@RequestMapping("/api") body
public class StudentRestController {
ol…dler
@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(StudentNotFoundException exc) {
Step 4: Add exception handler
method Exception
File: StudentRestController.java
Exception
Type of
the
response type
to handle /
@handler
RestC on t r o
m e t h
@RequestMapping("/api") body catch
public class StudentRestController {
ol…dler
@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(StudentNotFoundException exc) {
Step 4: Add exception handler
method
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class
StudentRestController {

@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(StudentNotFoundException exc) {

StudentErrorResponse error = new StudentErrorResponse();


Step 4: Add exception handler
method
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class
StudentRestController {

@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(StudentNotFoundException exc) {

StudentErrorResponse error = new StudentErrorResponse();


Step 4: Add exception handler
method
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class
StudentRestController {

@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(StudentNotFoundException exc) {

StudentErrorResponse error = new StudentErrorResponse();

error.setStatus(HttpStatus.NOT_FOUND.value());
Step 4: Add exception handler
method
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class
StudentRestController {

@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(StudentNotFoundException exc) {

StudentErrorResponse error = new StudentErrorResponse();

error.setStatus(HttpStatus.NOT_FOUND.value());
error.setMessage(exc.getMessage());
Step 4: Add exception handler
method
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class
StudentRestController {

@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(StudentNotFoundException exc) {

StudentErrorResponse error = new StudentErrorResponse();

error.setStatus(HttpStatus.NOT_FOUND.value());
error.setMessage(exc.getMessage());
error.setTimeStamp(System.currentTimeMillis());
Step 4: Add exception handler
method
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class
StudentRestController {

@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(StudentNotFoundException exc) {

StudentErrorResponse error = new StudentErrorResponse();

error.setStatus(HttpStatus.NOT_FOUND.value());
error.setMessage(exc.getMessage());
error.setTimeStamp(System.currentTimeMillis());
Step 4: Add exception handler
method
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class
StudentRestController {

@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(StudentNotFoundException exc) {

StudentErrorResponse error = new StudentErrorResponse();

error.setStatus(HttpStatus.NOT_FOUND.value());
error.setMessage(exc.getMessage());
error.setTimeStamp(System.currentTimeMillis());

return new ResponseEntity<>(error,


} HttpStatus.NOT_FOUND);

}
Step 4: Add exception handler
method
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class
StudentRestController {

@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(StudentNotFoundException exc) {

StudentErrorResponse error = new StudentErrorResponse();

error.setStatus(HttpStatus.NOT_FOUND.value());
error.setMessage(exc.getMessage());
error.setTimeStamp(System.currentTimeMillis());

return new ResponseEntity<>(error,


} HttpStatus.NOT_FOUND);

} Bod
y
Step 4: Add exception handler
method
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class
StudentRestController {

@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(StudentNotFoundException exc) {

StudentErrorResponse error = new StudentErrorResponse();

error.setStatus(HttpStatus.NOT_FOUND.value());
error.setMessage(exc.getMessage());
error.setTimeStamp(System.currentTimeMillis());

return new ResponseEntity<>(error,


} HttpStatus.NOT_FOUND);

} Bod Status
y code
Step 4: Add exception handler
method
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class
StudentRestController {

@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(StudentNotFoundException exc) {

StudentErrorResponse error = new StudentErrorResponse();

error.setStatus(HttpStatus.NOT_FOUND.value());
error.setMessage(exc.getMessage());
error.setTimeStamp(System.currentTimeMillis());

return new ResponseEntity<>(error,


} HttpStatus.NOT_FOUND);

} Bod Status
y code
Spring REST Exception
Handling
REST
Servi
/api/students/9999
ce
RES
T
Clie
nt
Spring REST Exception
Handling
Bad REST
data
Servi
/api/students/9999
ce
RES
T
Clie
nt
Spring REST Exception
Handling
Bad REST
data
Servi
/api/students/9999
ce
RES T
T h
r
Clie o
nt w

e
x
c
e
p
Spring REST Exception
Handling
Bad REST
data
Servi
/api/students/9999
ce
RES T
T h
Excepti r
Clie on
o
Handle
nt r
w

e
x
c
e
p
Spring REST - Global Exception
Handling

HiLCoE school of Computer science and technology


Spring REST Exception
Handling
Bad REST
data
Servi
/api/students/9999
ce
RES T
T h
Excepti r
Clie on
o
Handle
nt r
w

e
x
c
e
p
It works,
but …
It works,
but …
• Exception handler code is only for the specific REST
controller
It works,
but …
• Exception handler code is only for the specific REST
controller

• Can't be reused by other


controllers :-(
It works,
but …
• Exception handler code is only for the specific REST
controller
Large projects
• Can't be reused by other will have
controllers :-( multiple
controllers
It works,
but …
• Exception handler code is only for the specific REST
controller
Large projects
• Can't be reused by other will have
controllers :-( multiple
controllers

• We need global exception


handlers
It works,
but …
• Exception handler code is only for the specific REST
controller
Large projects
• Can't be reused by other will have
controllers :-( multiple
controllers

• We need global exception


handlers
• Promotes reuse
It works,
but …
• Exception handler code is only for the specific REST
controller
Large projects
• Can't be reused by other will have
controllers :-( multiple
controllers

• We need global exception


handlers
• Promotes reuse
• Centralizes exception
handling
Spring
@ControllerAdvice
Spring
@ControllerAdvice
• @ControllerAdvice is similar to an interceptor /
filter
Spring
@ControllerAdvice
• @ControllerAdvice is similar to an interceptor /
filter

• Pre-process requests to
controllers
Spring
@ControllerAdvice
• @ControllerAdvice is similar to an interceptor /
filter

• Pre-process requests to
controllers

• Post-process responses to handle


exceptions
Spring
@ControllerAdvice
• @ControllerAdvice is similar to an interceptor /
filter

• Pre-process requests to
controllers

• Post-process responses to handle


exceptions

• Perfect for global exception


handling
Spring
@ControllerAdvice
• @ControllerAdvice is similar to an interceptor /
filter

• Pre-process requests to
controllers Real-time
use of
• Post-process responses to handle AOP
exceptions

• Perfect for global exception


handling
Spring REST Exception
Handling
REST
Servi
ce
RES
T
Clie
nt
Spring REST Exception
Handling
REST
Servi
ce
/api/students/9999

RES
T
Clie
nt
Spring REST Exception
Handling
Controll REST
er Servi
Advice
ce
/api/students/9999

RES
T
Clie
nt
Spring REST Exception
Handling
Controll REST
er Servi
Advice
ce
/api/students/9999

RES
T
Clie
nt
Spring REST Exception
Handling
Controll REST
er Servi
Advice
ce
/api/students/9999

RES
T Throw
exception

Clie
nt
Spring REST Exception
Handling
Controll REST
er Servi
Advice
ce
/api/students/9999

RES
T Throw
exception

Clie
nt
Spring REST Exception
Handling
Controll REST
er Servi
Advice
ce
/api/students/9999

RES
T Excepti Throw
exception
on
Clie Handler
(s)
nt ..
.

..
.
Spring REST Exception
Handling
Controll REST
er Servi
Advice
ce
/api/students/9999

RES
T Excepti Throw
exception
on
Clie Handler
(s)
nt ..
.

..
.
Spring REST Exception
Handling
Controll REST
er Servi
Advice
ce
/api/students/9999

RES
T Excepti Throw
exception
on
Clie Handler
(s)
nt ..
.

..
.
Development Step-
By-St
ep

Process
Development Step-
By-St
ep

Process
1. Create new
@ControllerAdvice

HiLCoE school of Computer science and technology


www.luv2code.co
m
Development Step-
By-St
ep

Process
1. Create new @ControllerAdvice

2.Refactor RESTservice … remove exception


handling code
Development Step-
By-St
ep

Process
1. Create new @ControllerAdvice

2.Refactor RESTservice … remove exception


handling code

3. Add exception handling code to


@ControllerAdvice
Step 1: Create new
@ControllerAdvice
File: StudentRestExceptionHandler.java
Step 1: Create new
@ControllerAdvice
File: StudentRestExceptionHandler.java

@ControllerAdvice
public class StudentRestExceptionHandler {

}
Step 2: Refactor - remove exception
handling
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class
StudentRestController {

@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(StudentNotFoundException exc) {

StudentErrorResponse error = new StudentErrorResponse();

error.setStatus(HttpStatus.NOT_FOUND.value());
error.setMessage(exc.getMessage());
error.setTimeStamp(System.currentTimeMillis());

return new ResponseEntity<>(error,


} HttpStatus.NOT_FOUND);

}
Step 2: Refactor - remove exception
handling
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class
StudentRestController {

@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(StudentNotFoundException exc) {

StudentErrorResponse error = new StudentErrorResponse();

error.setStatus(HttpStatus.NOT_FOUND.value());
error.setMessage(exc.getMessage());
error.setTimeStamp(System.currentTimeMillis());

return new ResponseEntity<>(error,


} HttpStatus.NOT_FOUND);

}
Step 2: Refactor - remove exception
handling
File: StudentRestController.java

@RestController
Remo
@RequestMapping("/api") ve
this
public class
StudentRestController { code

@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(StudentNotFoundException exc) {

StudentErrorResponse error = new StudentErrorResponse();

error.setStatus(HttpStatus.NOT_FOUND.value());
error.setMessage(exc.getMessage());
error.setTimeStamp(System.currentTimeMillis());

return new ResponseEntity<>(error,


} HttpStatus.NOT_FOUND);

}
Step 3: Add exception handler to
@ControllerAdvice
File: StudentRestExceptionHandler.java

@ControllerAdvice
public class StudentRestExceptionHandler {

@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(StudentNotFoundException exc) {

StudentErrorResponse error = new StudentErrorResponse();

error.setStatus(HttpStatus.NOT_FOUND.value());
error.setMessage(exc.getMessage());
error.setTimeStamp(System.
());

return new ResponseEntity<>(error,


HttpStatus.NOT_FOUND);
}
}
Step 3: Add exception handler to
@ControllerAdvice
File: StudentRestExceptionHandler.java

@ControllerAdvice
public class StudentRestExceptionHandler {

@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(StudentNotFoundException exc) {

StudentErrorResponse error = new StudentErrorResponse();

error.setStatus(HttpStatus.NOT_FOUND.value());
error.setMessage(exc.getMessage());
error.setTimeStamp(System.
());

} return new ResponseEntity<>(error,


HttpStatus.NOT_FOUND);
}
Step 3: Add exception handler to
@ControllerAdvice
File: StudentRestExceptionHandler.java Same
code as
@ControllerAdvice before
public class StudentRestExceptionHandler {

@ExceptionHandler
public ResponseEntity<StudentErrorResponse> handleException(StudentNotFoundException exc) {

StudentErrorResponse error = new StudentErrorResponse();

error.setStatus(HttpStatus.NOT_FOUND.value());
error.setMessage(exc.getMessage());
error.setTimeStamp(System.
());

return new ResponseEntity<>(error,


HttpStatus.NOT_FOUND);
} }
Spring REST Exception
Handling
REST
Servi
ce
RES
T
Clie
nt
Spring REST Exception
Handling
REST
Servi
ce
/api/students/9999

RES
T
Clie
nt
Spring REST Exception
Handling
Controll REST
er Servi
Advice
ce
/api/students/9999

RES
T
Clie
nt
Spring REST Exception
Handling
Controll REST
er Servi
Advice
ce
/api/students/9999

RES
T
Clie
nt
Spring REST Exception
Handling
Controll REST
er Servi
Advice
ce
/api/students/9999

RES
T Throw
exception

Clie
nt
Spring REST Exception
Handling
Controll REST
er Servi
Advice
ce
/api/students/9999

RES
T Throw
exception

Clie
nt
Spring REST Exception
Handling
Controll REST
er Servi
Advice
ce
/api/students/9999

RES
T Excepti Throw
exception
on
Clie Handler
(s)
nt ..
.

..
.

www.luv2code.co
m
Spring REST Exception
Handling
Controll REST
er Servi
Advice
ce
/api/students/9999

RES
T Excepti Throw
exception
on
Clie Handler
(s)
nt ..
.

..
.
Spring REST Exception
Handling
Controll REST
er Servi
Advice
ce
/api/students/9999

RES
T Excepti Throw
exception
on
Clie Handler
(s)
nt ..
.

..
.
Spring REST API
Design

HiLCoE school of Computer science and technology


REST API
Design
REST API
Design
• For real-time projects, who will use
your API?
REST API
Design
• For real-time projects, who will use
your API?

• Also, how will they use your


API?
REST API
Design
• For real-time projects, who will use
your API?

• Also, how will they use your


API?

• Design the API based on


requirements
API Design Step-
By-St
ep

Process
API Design Step-
By-St
ep

Process
1. Review API
requirements

HiLCoE school of Computer science and technology


API Design Step-
By-St
ep

Process
1. Review API requirements

2. Identify main
resource / entity
API Design Step-
By-St
ep

Process
1. Review API requirements

2. Identify main resource /


entity

3. Use HTTP methods to assign action


on resource
Step 1: Review API
Requirements
Step 1: Review API
Requirements From the Boss

Create a REST API for the


Customer Relationship Management (CRM)
system
Step 1: Review API
Requirements From the Boss

Create a REST API for the


Customer Relationship Management (CRM)
system

REST clients should be able to


Step 1: Review API
Requirements From the Boss

Create a REST API for the


Customer Relationship Management (CRM)
system

REST clients should be able to


• Get a list of customers
Step 1: Review API
Requirements From the Boss

Create a REST API for the


Customer Relationship Management (CRM)
system

REST clients should be able to


• Get a list of customers
• Get a single customer by id
Step 1: Review API
Requirements From the Boss

Create a REST API for the


Customer Relationship Management (CRM)
system

REST clients should be able to


• Get a list of customers
• Get a single customer by id
• Add a new customer
Step 1: Review API
Requirements From the Boss

Create a REST API for the


Customer Relationship Management (CRM)
system

REST clients should be able to


• Get a list of customers
• Get a single customer by id
• Add a new customer
• Update a customer
Step 1: Review API
Requirements From the Boss

Create a REST API for the


Customer Relationship Management (CRM)
system

REST clients should be able to


• Get a list of customers
• Get a single customer by id
• Add a new customer
• Update a customer
• Delete a customer
Step 1: Review API
Requirements From the Boss

Create a REST API for the


Customer Relationship Management (CRM)
system
REST clients should be able
to
• Get a list of customers
• Get a single customer by id
Full
• Add a new customer CRUD
• Update a customer
• Delete a customer
Step 2: Identify main
resource / entity
Step 2: Identify main
resource / entity
• To identify main resource / entity, look for the most
prominent "noun"
Step 2: Identify main
resource / entity
• To identify main resource / entity, look for the most
prominent "noun"

• For our project, it is


"customer"
Step 2: Identify main
resource / entity
• To identify main resource / entity, look for the most
prominent "noun"

• For our project, it is


"customer"

• Convention is to use plural form of resource / entity:


customers
Step 2: Identify main
resource / entity
• To identify main resource / entity, look for the most
prominent "noun"

• For our project, it is


"customer"

• Convention is to use plural form of resource / entity:


customers

/api/customers
Step 3: Use HTTP methods to assign action
on resource
Step 3: Use HTTP methods to assign action
on resource
HTTP Method CRUD Action
Step 3: Use HTTP methods to assign action
on resource
HTTP Method CRUD Action
POST Create a new entity
Step 3: Use HTTP methods to assign action
on resource
HTTP Method CRUD Action
POST Create a new entity
GET Read a list of entities or single entity
Step 3: Use HTTP methods to assign action
on resource
HTTP Method CRUD Action
POST Create a new entity
GET Read a list of entities or single entity
PUT Update an existing entity
Step 3: Use HTTP methods to assign action
on resource
HTTP Method CRUD Action
POST Create a new entity
GET Read a list of entities or single entity
PUT Update an existing entity
DELETE Delete an existing entity
Step 3: Use HTTP methods to assign action
on resource
HTTP Method CRUD Action
POST Create a new entity
GET Read a list of entities or single entity
PUT Update an existing entity
DELETE Delete an existing entity

Full
CRUD
CRUD Endpoint
Examples
CRUD Endpoint
Examples
HTTP Method Endpoint CRUD Action
CRUD Endpoint
Examples
HTTP Method Endpoint CRUD Action
POST /api/customers Create a new customer
CRUD Endpoint
Examples
HTTP Method Endpoint CRUD Action
POST /api/customers Create a new customer
GET /api/customers Read a list of customers
CRUD Endpoint
Examples
HTTP Method Endpoint CRUD Action
POST /api/customers Create a new customer
GET /api/customers Read a list of customers
GET /api/customers/{customerId} Read a single customer
CRUD Endpoint
Examples
HTTP Method Endpoint CRUD Action
POST /api/customers Create a new customer
GET /api/customers Read a list of customers
GET /api/customers/{customerId} Read a single customer
PUT /api/customers Update an existing customer
CRUD Endpoint
Examples
HTTP Method Endpoint CRUD Action
POST /api/customers Create a new customer
GET /api/customers Read a list of customers
GET /api/customers/{customerId} Read a single customer
PUT /api/customers Update an existing customer
DELETE /api/customers/{customerId} Delete an existing customer
CRUD Endpoint
Examples
HTTP Method Endpoint CRUD Action
POST /api/customers Create a new customer
GET /api/customers Read a list of customers
GET /api/customers/{customerId} Read a single customer
PUT /api/customers Update an existing customer
DELETE /api/customers/{customerId} Delete an existing customer

For POST and PUT,


we will send customer data as JSON in request
message body
Anti-
Patterns
Anti-
Patterns
• DO NOT DO THIS … these are REST anti-patterns, bad
practice
Anti-
Patterns
• DO NOT DO THIS … these are REST anti-patterns, bad
practice

/api/customersList
/api/deleteCustomer
/api/addCustomer
/api/updateCustomer
Anti-
Patterns
• DO NOT DO THIS … these are REST anti-patterns, bad
practice

/api/customersList
/api/deleteCustomer
/api/addCustomer
/api/updateCustomer

Don't include actions in the


endpoint
Anti-
Patterns
• DO NOT DO THIS … these are REST anti-patterns, bad
practice

/api/customersList
/api/deleteCustomer
/api/addCustomer
/api/updateCustomer Instead, use
HTTP
methods to
Don't include actions in the assign
endpoint
actions
CRM Real-Time
Project
CRM Real-Time
Project
HTTP Method Endpoint CRUD Action
POST /api/customers Create a new customer
GET /api/customers Read a list of customers
GET /api/customers/{customerId} Read a single customer
PUT /api/customers Update an existing customer
DELETE /api/customers/{customerId} Delete an existing customer
CRM Real-Time
Project
HTTP Method Endpoint CRUD Action
POST /api/customers Create a new customer
GET /api/customers Read a list of customers
GET /api/customers/{customerId} Read a single customer
PUT /api/customers Update an existing customer
DELETE /api/customers/{customerId} Delete an existing customer

CRM
Service
(spring-rest)
More API
Examples
More API
Examples
• On the following slides, we’ll look at APIs from other real-
time projects
More API
Examples
• On the following slides, we’ll look at APIs from other real-
time projects

• PayPa
l
More API
Examples
• On the following slides, we’ll look at APIs from other real-
time projects

• PayPa
l

• GitHu
b
More API
Examples
• On the following slides, we’ll look at APIs from other real-
time projects

• PayPa
l

• GitHu
b

• SalesFor
ce
PayP
al
PayP
al
• PayPal Invoicing
API
PayP
al
• PayPal Invoicing
API
• https://developer.paypal.com/docs/api/invoicing/
PayP
al
• PayPal Invoicing
API
• https://developer.paypal.com/docs/api/invoicing/
GitHu
b
GitHu
b
• GitHub Repositories
API
GitHu
b
• GitHub Repositories
API
• https://developer.github.com/v3/repos/#repositories
GitHu
b
• GitHub Repositories
API
• https://developer.github.com/v3/repos/#repositories

Create a new repository List your repositories

Delete a repository Get a repository


SalesForce REST
API
SalesForce REST
API
• Industries REST
API
SalesForce REST
API
• Industries REST
API
• https://sforce.co/2J40ALH
SalesForce REST
API
• Industries REST
API
• https://sforce.co/2J40ALH

Retrieve All Individuals


GET /services/apexrest/v1/individual/

Retrieve One Individual


GET /services/apexrest/v1/individual/{individual_id}

Create an individual
POST /services/apexrest/clinic01/v1/individual/

Update an individual
PUT /services/apexrest/clinic01/v1/individual/
Spring REST API - Real Time
Project

HiLCoE school of Computer science and technology


API Requirements -
Refresher
API Requirements -
Refresher From the Boss

Create a REST API for the


Customer Relationship Management (CRM)
system.

REST clients should be able to


• Get a list of customers
• Get a single customer by id
• Add a new customer
• Update a customer
• Delete a customer
Real-Time
Project
HTTP Method CRUD Action
POST /api/customers Create a new customer
GET /api/customers Read a list of customers
GET /api/customers/{customerId} Read a single customer
PUT /api/customers Update an existing customer
DELETE /api/customers/{customerId} Delete an existing customer
Application
Architecture
Application
Architecture

CRM
Service
(spring-rest)
Application
Architecture

CRM
Service
(spring-rest)
Application
Architecture

CRM
Customer Customer
Service
Service DAO
(spring-rest)
Application Reuse code from

Architecture
previous CRM
web project

CRM
Customer Customer
Service
Service DAO
(spring-rest)
Application Reuse code from

Architecture
previous CRM
web project

CRM
Customer Customer
Service
Service DAO
(spring-rest)

New code that we will


create
Project Set
Up
Project Set
Up
• We will download a Maven starter
project
Project Set
Up
• We will download a Maven starter
project

• Includes CustomerService, CustomerDAO and


Customer entity
Project Set
Up
• We will download a Maven starter
project

• Includes CustomerService, CustomerDAO and


Customer entity
• We created all of this code already
Project Set
Up
• We will download a Maven starter
project

• Includes CustomerService, CustomerDAO and


Customer entity
• We created all of this code already

• Allows us to focus on creating CRM REST


Service
Development Step-
By-St
ep

Process
Development Step-
By-St
ep

Process
Development Step-
By-St
ep

Process
1. Get
customers

HiLCoE school of Computer science and technology


Development Step-
By-St
ep

Process
1. Get customers

2. Get single
customer by
ID
Development Step-
By-St
ep

Process
1. Get customers

2. Get single
customer by
ID

3. Add a new customer


Development Step-
By-St
ep

Process
1. Get customers

2. Get single
customer by
ID

3. Add a new customer

4. Update an existing
customer
Development Step-
By-St
ep

Process
1. Get customers

2. Get single
customer by
ID

3. Add a new customer

4. Update an existing
customer

5. Delete an existing
customer
Code Review Step-
By-St
ep

1. pom.xml file

2. All Java Config

3. Configuration file for database


connection

4. Hibernate Entity class: Customer

5. DAO: CustomerDAO …

6. Service: CustomerService …
Spring CRM REST - Get
Customers

HiLCoE school of Computer science and technology


Application
Interaction
Application
Interaction

RES
T
Clie
nt
Application
Interaction
Custom
er
REST
RES Controll
T er
Clie
nt
Application
Interaction
Custom
er
GET /api/customers
REST
RES Controll
T er
Clie
nt
Application
Interaction
Custom
er
GET /api/customers
REST
RES Controll
T er
Clie
nt
Application
Architecture
Application
Architecture

Customer Customer
Service DAO
Application
Architecture

Customer
Customer Customer
REST
Service DAO
Controller
Application
Architecture

Customer
Customer Customer
REST
Service DAO
Controller

New code we are


developing
Development Step-
By-St
ep

Process
Development Step-
By-St
ep

Process
1. Create Customer REST
Controller

HiLCoE school of Computer science and technology


Development Step-
By-St
ep

Process
1. Create Customer REST
Controller

2. Autowire CustomerService
Development Step-
By-St
ep

Process
1. Create Customer REST
Controller

2. Autowire CustomerService

3. Add mapping for GET


/customers
Step 1: Create Customer REST
Controller
File: StudentRestController.java

@RestController
@RequestMapping("/api"
)
public class
CustomerRestController
// autowire the CustomerService
{ @Autowired
private CustomerService
customerService;

// add mapping for GET


/customers
@GetMapping("/customers")
public List<Customer>
getCustomers() {

} return
customerService.getCustomers();

}
Step 2: Autowire
CustomerService
File: StudentRestController.java

@RestController
@RequestMapping("/api"
)
public class
CustomerRestController
// autowire the CustomerService
{ @Autowired
private CustomerService
customerService;

// add mapping for GET /customers


@GetMapping("/customers")
public List<Customer> getCustomers() {

return
customerService.getCustomers();

} }
Step 2: Autowire
CustomerService
File: StudentRestController.java

@RestController
@RequestMapping("/api"
)
public class
CustomerRestController
{

// autowire the
CustomerService @Autowired
// add mapping
private for GET /customers
CustomerService
customerService;
@GetMapping("/customers")
public List<Customer> getCustomers() {

return
customerService.getCustomers();

} }
Step 3: Add mapping for GET
/customers
File: StudentRestController.java

@RestController
@RequestMapping("/api"
)
public class
CustomerRestController
{

// autowire the
CustomerService @Autowired
// add mapping
private for GET /customers
CustomerService
customerService;
@GetMapping("/customers")
public List<Customer> getCustomers() {

return
customerService.getCustomers();

} }
Step 3: Add mapping for GET
/customers
File: StudentRestController.java

@RestController
@RequestMapping("/api"
)
public class
CustomerRestController
{

// autowire the
CustomerService @Autowired
private CustomerService
customerService;

// add mapping for GET


/customers
@GetMapping("/customers")
public List<Customer>
getCustomers() {

return
Spring CRM REST - Get Single
Customer

HiLCoE school of Computer science and technology


Application
Interaction
Application
Interaction

RES
T
Clie
nt
Application
Interaction
Custom
er
REST
RES
Controll
T
er
Clie
nt
Application
Interaction
Custom
GET /api/customers/{customerId}
er
REST
RES
Controll
T
er
Clie
nt
Application
Interaction
Custom
GET /api/customers/{customerId}
er
REST
RES
Controll
T
er
Clie
nt
Get Single
Customer
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class
CustomerRestController
{

// autowire the CustomerService


@Autowired
private CustomerService
customerService;
// add mapping for GET /customers/{customerId}

@GetMapping("/customers/{customerId}")
public Customer getCustomer(@PathVariable int customerId) {

Customer theCustomer = customerService.getCustomer(customerId);

return theCustomer;
}

}
Get Single
Customer
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class
CustomerRestController
{

// autowire the CustomerService


@Autowired
private CustomerService
customerService;
// add mapping for GET /customers/{customerId}

@GetMapping("/customers/{customerId}")
public Customer getCustomer(@PathVariable int customerId) {

Customer theCustomer = customerService.getCustomer(customerId);

return theCustomer;
}

}
Get Single
Customer
File: StudentRestController.java

@RestController
@RequestMapping("/api")
public class
CustomerRestController
{

// autowire the CustomerService


@Autowired
private CustomerService
customerService;

// add mapping for GET /customers/{customerId}

@GetMapping("/customers/{customerId}")
public Customer getCustomer(@PathVariable int
customerId) {

Customer theCustomer = customerService.getCustomer(customerId);

return theCustomer;
}

}
Spring CRM REST - Exception
Handling

HiLCoE school of Computer science and technology


Application
Interaction
Application
Interaction

RES
T
Clie
nt
Application
Interaction
CR
M
RES
RES T
T Contr
oller
Clie
nt
Application
Interaction
CR
M
GET /api/customers/9999
RES
RES T
T Contr
oller
Clie
nt
Application
Interaction Bad
Data CR
M
GET /api/customers/9999
RES
RES T
T Contr
oller
Clie
nt
Application
Interaction Bad
Data Controll CR
er M
GET /api/customers/9999
Advice RES
RES T
T Contr
oller
Clie
nt
Application
Interaction Bad
Data Controll CR
er M
GET /api/customers/9999
Advice RES
RES T
T Contr
oller
Clie
nt
Application
Interaction Bad
Data Controll CR
er M
GET /api/customers/9999
Advice RES
RES T
T Contr
oller
Clie
nt Throw
exception
Application
Interaction Bad
Data Controll CR
er M
GET /api/customers/9999
Advice RES
RES T
T Contr
oller
Clie
nt Throw
exception
Application
Interaction Bad
Data Controll CR
er M
GET /api/customers/9999
Advice RES
RES T
T Excepti
Contr
on oller
Clie Handler
(s)
nt ..
.
Throw
exception
..
.
Application
Interaction Bad
Data Controll CR
er M
GET /api/customers/9999
Advice RES
RES T
T Excepti
Contr
on oller
Clie Handler
(s)
nt ..
.
Throw
exception
..
.

Global Exception
Handler(s)
Application
Interaction Bad
Data Controll CR
er M
GET /api/customers/9999
Advice RES
RES T
T Excepti
Contr
on oller
Clie Handler
(s)
nt ..
.
Throw
exception
..
.

Global Exception
Handler(s)
Development Step-
By-St
ep

Process
Development Step-
By-St
ep

Process
1. Create a
custom error response
class

HiLCoE school of Computer science and technology


Development Step-
By-St
ep

Process
1. Create a custom error
response class

2. Create a custom exception


class
Development Step-
By-St
ep

Process
1. Create a custom error response class

2. Create a custom exception class

3. Update REST service to throw exception if customer


not found
Development Step-
By-St
ep

Process
1. Create a custom error response class

2. Create a custom exception class

3. Update REST service to throw exception if customer


not found

4. Add an exception handler methods


using @ExceptionHandler
Spring CRM REST - Add
Customer

HiLCoE school of Computer science and technology


Real-Time Project –lab

HTTP Method CRUD Action


POST /api/customers Create a new customer
GET /api/customers Read a list of customers
GET /api/customers/{customerId} Read a single customer
PUT /api/customers Update an existing customer
DELETE /api/customers/{customerId} Delete an existing customer

You might also like