-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path08. REST API Notes.txt
More file actions
1177 lines (759 loc) · 29.4 KB
/
08. REST API Notes.txt
File metadata and controls
1177 lines (759 loc) · 29.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
==================================
RESTFul Services & Microservices
===================================
Pre-Requisite : Spring Boot
=====================
Course Content :
======================
Part- 1) RESTFul Services
=> What is Distributed Application
=> Distributed Technologies
=> REST Introduction
=> REST Architecture
=> XML & JAX-B API.
=> JSON & Jackson API
=> HTTP Protocol (Methods + Status Codes)
=> REST Architecture Principle
=> REST API Development (Provider Development)
=> What is RestController
=> GET + POST + PUT + DELETE Methods
=> Query Params & Path Params
=> Request Body & Response Body
=> REST API Testing using POSTMAN
=> Swagger
=> Rest Client Development (Consumer Development)
=> RestTemplate class (Sync)
=> WebClient ( Sync & Async )
=> Exception Handling in REST API
Part-2 ) Spring Security
=> Authetication
=> Authorization
=> Basic Authentication
=> OAuth 2.0
=> JWT
Part-3) Microservices with Spring Cloud
=> Monolith Architecture
=> Pros & Cons of Monolith
=> Microservices Introduction
=> Microservices Architecture
=> Pros & Cons of Microservices
=> Service Registry (Eureka Server)
=> Admin Server + Admin Client
=> Distributed Log Tracing (zipkin + sleuth)
=> API Gateway ( Filters + Rounting ) - CloudGateway
=> Fiegn Client (Interservice Communication)
=> Load Balancer (Ribbon)
=> Cicuit Breaker with Reselliance
=> Config Server
Part-4 : SPring Boot - Integrations
=> Spring Boot with Redis Cache Integration
=> Spring Boot with Kafka Integration
=> Spring Boot with Docker Integration
Course Duration : 45 Days
Class Timings : 7:30 PM - 9:00 PM (IST) (Mon-Sat)
Course Start Date : Today
Course Fee : 8,000 INR (Live Classes + Backup Videos + ClassNotes)
===================================================================================
Spring Boot & Microservies - 10,000 INR (5:00 PM IST Batch started one week ago)
===================================================================================
Spring Core
SPring Boot
Spring Data JPA
Web MVC
RESTFulservices
Security
Microservices
Integration
============================================================================
RESTFul Services & Microservies - 8000 INR (7:30 PM IST Batch started today)
============================================================================
RESTFulservices
Security
Microservices
Integration
==================================
What is Distributed Application ?
==================================
-> If one application is communicating with another application then they are called as Distributed Applications.
MakeMyTrip -----------> IRCTC
Passport App ---------> AAdhar App
Gpay / Phone Pay ------> Banking App
=> Distributed Applications are used for Business To Business Communication (B 2 B).
Note: Web Applications are used for Customer To Business Communication (C 2 B).
=========================
Distributed Technologies
=========================
1) CORBA
2) RMI
3) EJB
4) SOAP Based Webservices
5) RESTFul Services (trending)
Provider : The application which is providing services to other application (Resource)
Consumer : The application which is accessing services from other application (Client)
=============================
What is Intereoperability ?
=============================
=> Irrespective of language & platform if applications are communicating then they are called as Intereoperable applications.
Java <--------> Python
Python <------> .Net
.Net <-----> PHP
Note: By using RESTFUl Services we can develop Intereoperable applications.
=======
XML
======
-> XML stands for Extensible Markup Language
-> XML Govenred by w3c org
-> XML is platform independent and language independent
-> XML is used to exchange data between applications (webservices)
-> XML represents data in elements format
-> Every Element contains open tag and closed tag
<id>101</id>
<name>Ashok</name>
-> In XML we can use 2 types of elements
1) Simple element
2) Compound element
-> The element which represents data directley is called as simple element.
<id>101</id>
-> The element which represents child element(s) is called as Compound Element.
<person>
<fname>Ashok</fname>
<lname>Kumar</lname>
</person>
=============
JAX-B API
============
=> JAX-B stands for Java Architecture For XML binding
=> Using JAX-B API we can convert xml data to java object and java object to xml data.
Marshalling : Convert Java Object to XML data
Un-Marshalling : Convert XML data to Java Object
=> To perform Marshalling & Un-Marshalling we need to create Binding Classes.
=> Binding Class means the class which represents XML structure
Note: Upto JDK 1.8v JAX-B is part of JDK software. From JDK 1.9 version JAX-B removed from JDK.
Note: From java 1.9v or above versions should have jax-b dependency.
======================================== JAX-B Example ===============================================
@XmlRootElement
public class Person {
private Integer id;
private String name;
private String email;
private String gender;
private Address addr;
//setters & getters
}
public class Address {
private String city;
private String state;
private String country;
//setters & getters
}
public class MarshallDemo {
public static void main(String[] args) throws Exception {
Address addr = new Address();
addr.setCity("Hyd");
addr.setState("TG");
addr.setCountry("India");
Person p = new Person();
p.setId(101);
p.setName("Ashok");
p.setGender("Male");
p.setEmail("ashokitschool@gmail.com");
p.setAddr(addr);
JAXBContext context = JAXBContext.newInstance(Person.class);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(p, new File("person.xml"));
System.out.println("done.....");
}
}
public class UnmarshalDemo {
public static void main(String[] args) throws Exception {
JAXBContext context = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Person p = (Person) unmarshaller.unmarshal(new File("person.xml"));
System.out.println(p);
}
}
========================================================================================================
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
=======================================================================================================
=======
JSON
=======
=> JSON stands for Java Script Object Notation
=> JSON represents data in key-value format
=> JSON is light weight
=> JSON is Intereoperable (Platform & Language Independent)
=> We can use JSON structure to exchange data from one application to another application
Note: When compared with XML, JSON will take less memory
=> To work with JSON data we have below 3rd party APIs
1) Jackson (It is default in spring boot)
2) Gson (given by google)
=> Using above apis we can convert java object to json and json to java object
Serialization : Convert Java Object to JSON
De-Serialization : Convert JSON data to Java Object
=> Jackson API provided methods to perform operations java with json
ObjectMapper mapper = new ObjectMapper ( ) ;
mapper.writeValue(new File("person.json"), personObj);
Person p = mapper.readValue(new File("person.json"), Person.class);
============================== Jackson API Example ========================================
public class Address {
private String city;
private String state;
private String country;
// setters & getters
}
public class Passenger {
private String name;
private String from;
private String to;
private String gender;
private Address addr;
// setters & getters
}
public class JavaToJson {
public static void main(String[] args) throws Exception {
Address addr = new Address();
addr.setCity("Hyd");
addr.setState("TG");
addr.setCountry("India");
Passenger passenger = new Passenger();
passenger.setName("Raju");
passenger.setFrom("Hyd");
passenger.setTo("Delhi");
passenger.setGender("Male");
passenger.setAddr(addr);
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("passenger.json"), passenger);
System.out.println("Done....");
}
}
public class JsonToJava {
public static void main(String[] args) throws Exception{
ObjectMapper mapper = new ObjectMapper();
Passenger passenger = mapper.readValue(new File("passenger.json"), Passenger.class);
System.out.println(passenger);
}
}
=======================================GSON API Example ==========================================
Gson gson = new Gson();
String json = gson.toJson(passenger);
System.out.println(json);
Passenger p = gson.fromJson(new FileReader("passenger.json"), Passenger.class);
System.out.println(p);
===============
HTTP Protocol
==============
=> HTTP stands for Hypertext Transfer Protocol
=> HTTP acts as mediator between Client & Server
=> HTTP is a stateless protocol. It will treat every request as a new request.
Note: To develop REST API we should know below details about HTTP Protocol.
1) HTTP Methods
2) HTTP Status Codes
3) Http Request
4) HTTP Response
================
HTTP Methods
================
GET ===> To get data from server to client
POST ===> To send data from client to server
PUT ===> To update data at server
DELETE ===> To delete data from server
Note: Every REST API method/endpoint should be binded to HTTP Protocol method
=> getTicketData ( ) ---> HTTP GET Method ---> @GetMapping
=> bookTicket(..) ---> HTTP POST Method ----> @PostMapping
=> updateProduct (..) --> HTTP PUT Method ----> @PutMapping
=> deleteBook (..) ---> HTTP DELETE Method ---> @DeleteMapping
====================
HTTP Status Codes
====================
=> Server will send HTTP Status code to client in the response
=> HTTP Status codes will indicate how server processed our request
1XX (100 to 199) => Informational status code
2XX (200 to 299) => SUCCESS status code (OK)
3XX (300 to 399) => Redirectional
4XX (400 to 499) => Client Error
5XX (500 to 599) => Server Error
====================
HTTP Request Packet
====================
1) Request Line ( HTTP Method + Request URL )
Ex: GET www.irctc.com/ticket/13454
2) Request Header (Meta data)
Ex :
Content-Type = application/json
Accept = application/json
Authentication = uname:pwd
Token = sldfjdlsfyso
3) Request Body (Payload)
Ex: xml or json data
================
HTTP Response
================
1) Response Line ( Https Status Code + Status Msg )
Ex: 200 OK
2) Response Header (Meta data)
Content-Type : application/json
Content-Length : 100
Date: mm/dd/yyyy
3) Response Body (Payload)
Ex: xml data or json data
======================
REST API Development
======================
=> It is very simple to develop REST API using Spring Boot
=> Spring Boot provided 'web-starter' to develop both web & distributed apps
=> 'Web-Starter' will provide tomcat as default embedded server
Step-1) Create Spring-Starter Project with below dependency
*** springboot-starter-web
Step-2) Create Rest Controller class using @RestController
Step-3) Write the required methods & bind them to HTTP Protocol Request
Step-4) Run the boot application (it will run in embedded server)
Step-5) Test our REST Application using POSTMAN tool
===================
Media Types
==================
consumes : It represents in which format REST API method can take input
produces : It represets in which format REST API method can provide output
Content-Type Header : It represents in which format client sending data to REST API in req body
Accept Header : It represents in which format client expecting response from REST API.
==================================== Media Types ==================================
@XmlRootElement
@Data
public class Customer {
private String name;
private String email;
private String gender;
}
@RestController
public class CustomerRestController {
@GetMapping(
value="/customer",
produces = {"application/xml" , "application/json"}
)
public Customer getCustomer() {
Customer c = new Customer();
c.setName("John");
c.setEmail("john@gmail.com");
c.setGender("Male");
return c;
}
@PostMapping(
value = "/customer",
consumes = {"application/xml", "application/json"},
produces = {"text/plain"}
)
public ResponseEntity<String> addCustomer(@RequestBody Customer customer) {
System.out.println(customer);
// logic to insert customer in db
return new ResponseEntity<>("Customer Saved", HttpStatus.CREATED);
}
}
======================================================================================================
Requirement : Develop REST API to book train tickets. It should contain 2 below endpoints
1) BOOk Ticket -- POST Request
Input : Passenger Data
Output : Ticket data
consumes : xml & json
produces : xml & json
2) Get Ticket -- GET Request
Input : Ticket ID
Output : Ticket Data
consumes : N/A
produces : xml & json
=============================================
Development Procedure For Above Requirement
==============================================
1) Create Spring Boot Application with below dependencies
a) web-starter
b) lombok
c) devtools
2) Create Request and Response Binding classes
3) Create REST Controller class with Required Methods
4) Bind Rest controller methods to HTTP Request methods
5) Run our application with Embedded Server
6) Test our application with POSTMAN.
==============================
Passenger Data in JSON Format
==============================
{
"fname": "ashok",
"lname": "kumar",
"from": "Hyd",
"to" : "Delhi",
"doj" : "30/03/2023",
"trainNum": "8878"
}
==========
Swagger
==========
=> In Distributed applications two actors will be available
1) Provider
2) Consumer
=> Provider will be developed by one company
=> Consumer will be developed by another company
=> If consumer wants to access provider, consumer side dev team should know provider information
-> What is provider api url ?
-> What operations (methods) provider having ?
-> Operations are binded to which Request Type (GET or POST or PUT or DELETE )?
-> What input provider expecting from consumer ?
-> What output provider will give to consumer ?
-> Which data form provider will support for input and output ?
Note: If consumer side dev team having all the above information then only then can start consumer side development.
Note: Provider side dev team should provide API documentation to consumer side dev team.
=> Swagger is used to generate API documentation.
=> Swagger is a third party library which is used to generate REST API documentation.
Note: Using Swagger Documentation Consumer side dev team will understand Provider API information.
================================================
Steps to add Swagger Documentation for REST API
================================================
1) Add swagger & swagger-ui dependencies in project pom.xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
2) Create SwaggerConfig class to generate documentation
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket apiDoc() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("in.ashokit.rest"))
.paths(PathSelectors.any())
.build();
}
}
3) Run the application and access Swagger documentation in browser.
Json Doc URL : http://localhost:8080/v2/api-docs
UI Doc URL : http://localhost:8080/swagger-ui.html#/
NOte: Using Swagger UI we can test REST API functionality just like POSTMAN.
1) What is Distributed Application
2) Distributed Technologies
3) What is Intereoperability ?
4) What is HTTP Protocol ?
5) HTTP Request Packet
6) HTTP Response Packet
7) HTTP Methods
8) HTTP Status Codes
9) XML & JAX-B API
10) JSON & JACKSON API / GSON api
11) REST API Development ( @RestController )
12) REST API Testing with POSTMAN
13) MEDIA TYPES (conumes & produces)
14) Content-Type & Accept headers
15) Swagger Documentation
16) Query Parameter (@RequestParam)
17) Path Variable (@PathVariable)
18) @RequestBody
19) ResponseEntity (combine resp body + http status code)
20) REST API Deployment in AWS Cloud
===========================
REST Client Development
===========================
=> The application which is accessing other applications is called as REST Client.
=> In Spring Boot we can develop REST Client in 3 ways
1) RestTemplate class (Synchronus)
2) WebClient interface (Synchronus & Async) (introduced in spring 5.x version)
3) FeiginClient interface (spring cloud)
Note: From Spring 5.x version onwards we have to use WebClient instead of RestTemplate.
-------------------------------------------application.properties----------------------------
spring.mvc.view.prefix=/views/
spring.mvc.view.suffix=.jsp
irctc.endpoint.book.ticket=http://3.110.190.17:8080/ticket
irctc.endpoint.get.ticket=http://3.110.190.17:8080/ticket/{ticketId}
-----------------------------------------------------------------------------------------
@Service
public class MakeMyTripService {
@Value("${irctc.endpoint.book.ticket}")
private String IRCTC_BOOK_TICKET_URL;
@Value("${irctc.endpoint.get.ticket}")
private String IRCTC_GET_TICKET_URL;
public Ticket getTicketInfo(String ticketId) {
RestTemplate rt = new RestTemplate();
ResponseEntity<Ticket> responseEntity =
rt.getForEntity(IRCTC_GET_TICKET_URL, Ticket.class, ticketId);
int status = responseEntity.getStatusCodeValue();
if (status == 200) {
Ticket ticket = responseEntity.getBody();
return ticket;
}
return null;
}
public Ticket processTicketBooking(Passenger passenger) {
RestTemplate rt = new RestTemplate();
ResponseEntity<Ticket> responseEntity =
rt.postForEntity(IRCTC_BOOK_TICKET_URL, passenger, Ticket.class);
int statusCode = responseEntity.getStatusCodeValue();
if (statusCode == 200) {
Ticket ticket = responseEntity.getBody();
return ticket;
}
return null;
}
}
-------------------------------------------------------------------------------------------------
IRCTC API Doc URL : http://3.110.190.17:8080/swagger-ui.html
-------------------------------------------------------------------------------------------------
============
WebClient
============
-> WebClient is a predefined interface introduced in Spring 5.x version
-> Using WebClient interface we can develop REST Client logics
-> WebClient supports both sync & async communication.
Sync : Blocking Thread (After sending request we have to wait for response)
Async : Non Blocking Thread (After sending request we no need to wait for response)
RestTemplate (C) : spring-boot-starter-web
WebClient (I) : spring-boot-starter-webflux
=============================== RestClient development with WebClient ====================================
@Service
public class MakeMyTripService {
@Value("${irctc.endpoint.book.ticket}")
private String IRCTC_BOOK_TICKET_URL;
@Value("${irctc.endpoint.get.ticket}")
private String IRCTC_GET_TICKET_URL;
public Ticket getTicketInfo(String ticketId) {
WebClient webClient = WebClient.create(); // get WeClient instance
Ticket ticket = webClient.get() // represents HTTP GET request
.uri(IRCTC_GET_TICKET_URL, ticketId) // ENDPOINT URL
.accept(MediaType.APPLICATION_JSON)
.retrieve() // take resp from response body
.bodyToMono(Ticket.class) // bind resp body data to java obj
.block(); // make sync call
if(ticket!=null) {
return ticket;
}
return null;
}
public Ticket processTicketBooking(Passenger passenger) {
WebClient webClient = WebClient.create(); // get WeClient instance
Ticket ticket = webClient.post()
.uri(IRCTC_BOOK_TICKET_URL)
.body(BodyInserters.fromValue(passenger))
.header("Content-Type","application/json")
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Ticket.class)
.block();
if(ticket!=null) {
return ticket;
}
return null;
}
}
===========================
Async Client Development
===========================
package in.ashokit;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
@Service
public class MakeMyTripService {
@Value("${irctc.endpoint.book.ticket}")
private String IRCTC_BOOK_TICKET_URL;
@Value("${irctc.endpoint.get.ticket}")
private String IRCTC_GET_TICKET_URL;
public void getTicketInfoSync(String ticketId) {
System.out.println("Sync - method started....");
WebClient client = WebClient.create();
String response = client.get()
.uri(IRCTC_GET_TICKET_URL, ticketId)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(String.class)
.block(); // wait for response
System.out.println(response);
System.out.println("Sync - method ended....");
}
public void getTicketAsync(String ticketId) {
System.out.println("Async method execution started.....");
WebClient client = WebClient.create();
client.get()
.uri(IRCTC_GET_TICKET_URL, ticketId)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(String.class)
.subscribe(response -> handleResponse(response));
System.out.println("Async method execution ended.....");
}
public void handleResponse(String response) {
System.out.println(response);
}
}
=====================================================================================================
=================
Spring Data REST
=================
=> It is used to simplfiy REST API development
=> We no need to create REST Controllers to perform CRUD operations with DB table when we use Spring Data REST.
=> To use Data-REST in our project we need to add below dependency in pom.xml (REST REpositories)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
-----------------------------------------------------------------
@Entity
@Table(name = "book_tbl")
@Data
public class Book {
@Id
private Integer id;
private String name;
private Double price;
}
----------------------------------------------------------------------------------------------
@RepositoryRestResource(path = "books")
public interface BookRepository extends JpaRepository<Book, Integer> {
public List<Book> findByNameContaining(@Param("name") String name);
}
----------------------------------------------------------------------------------------------
@Configuration
public class MyDataRestConfig implements RepositoryRestConfigurer {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config, CorsRegistry cors) {
HttpMethod[] unsupportedMethods = { HttpMethod.PUT, HttpMethod.DELETE };
config.getExposureConfiguration()
.forDomainType(Book.class)
.withItemExposure((metadata, http) -> http.disable(unsupportedMethods))
.withCollectionExposure((metadata,http) -> http.disable(unsupportedMethods));
}
}
---------------------------------------------------------------------------------------------
============================
REST API Exception Handling
============================
-> Exception means un-expected and un-wanted situation
-> Exception will cause abnormal termination of our program
-> To achieve graceful termination, we need to handle exceptions in our application