Posts

Showing posts from June, 2023

Delete the Resource from REST API

 Delete Resource from REST API public void deleteById( int id ) { Predicate<? super User> predicate = user -> user .getId().equals( id ); users .removeIf( predicate ); }

Generic Exception Handling for all the resources

Generic Exception Handling for all the resources we need custom exception structure while getting exception resonse ErrorDetails.java: for creating your Custom Response Structure public class ErrorDetails { private LocalDateTime timestamp ; private String message ; private String details ; private String errorGenerator ; public ErrorDetails(LocalDateTime timestamp , String message , String details , String errorGenerator ) { super (); this . timestamp = timestamp ; this . message = message ; this . details = details ; this . errorGenerator = errorGenerator ; } public LocalDateTime getTimestamp() { return timestamp ; } public String getMessage() { return message ; } public String getDetails() { return details ; } public String getErrorGenerator() { return errorGenerator ; } } CustomizedResponseEntityExceptionHandler.java class is created similar formate of ResponseEntityExceptionHandler class to achive centralized fo...

404 if Not Found the resource in Spring Boot

Image
 For the Rest API we have to add proper Error Code as response to identify the Response UserResourceController.java @RestController public class UserResourceController { private UserDaoService userDaoService ; @GetMapping ( "/users/{id}" ) public User retrieveUser( @PathVariable int id ) throws UserPrincipalNotFoundException { User user = userDaoService .findOne( id ); return user ;      } } UserDaoService.java @Component public class UserDaoService { private static List<User> users = new ArrayList<>(); private static int usersCount = 0; static { users .add( new User(++ usersCount , "Khan" , LocalDate. now ().minusYears(25))); users .add( new User(++ usersCount , "pathan" , LocalDate. now ().minusYears(50))); users .add( new User(++ usersCount , "tigher" , LocalDate. now ().minusYears(52))); users .add( new User(++ usersCount , "jim" , LocalDate. now ().minusYears(40))...

Enhance Post Method with method Return to Correct HTTP status Code and Location

Image
 Response Status for REST API 404 Response is not Found 500 Response is Server Error 400 Response is Validation Error 200 Response is Success 201 Response is Created 204 Response is No Content 401 Response is Unauthorized (when authorization failed) 400 Response is Bad Request (such as validation error) How to Give Response as 201 when resource is created  @ PostMapping ( "/users" ) public ResponseEntity<User> addUser( @ RequestBody User user ) { User savedUser = userDaoService .save( user ); return ResponseEntity. created ( null ).build(); } postman request for given API call try to add new User name = Kapil with given birthdate =1997-06-27 Get a Response status as 201 Lets add the location URI as well into the Response header @ PostMapping ( "/users" ) public ResponseEntity<User> addUser( @ RequestBody User user ) { User savedUser = userDaoService .save( user ); URI location = ServletUriComponentsBuilder. fromCurrentRequest ()...

Designing Social Media Application using Spring Boot

  Designing Social Media Application using Spring Boot Rest Api 1. Build a Rest Api For a social Media Application  2. Key Resources: Users Posts 3. Key Details: User: id ,name, birthdate  Post: id, description for we would create API Around the Users and Posts, as part of API we would be perform operations like  delete user , update user,  add new user add post for specific user, update post for specific user, delete post for specific  user etc. Request Methods for REST API GET PUT POST DELETE PATCH USER Rest API: Retrieve All Users: GET/users Create User POST/users Retrieve One User GET/users/{id} ==> /user/1 Delete User DELETE /users/{id} ==> /user/1 POST REST API inside your User Retrieve  All Posts of the specific User GET/users/{id}/posts Create a Post for a User POST/users/{id}/posts Retrieve Detail of a post GET/users/{id}/posts/{post_id} We can user Singular or Plurals while using Request URL we will follow Plurals as it would...

How to User Path variable

  How to User Path variable @ PathVariable   is used for add the variable in the path of your URL and use into the code  @RestController @RequestMapping (path = "/by" ) public class ByWorldController { @GetMapping (path = "/hello-world/path-variable/{name}/{gender}" ) public HelloWorldBean helloWorldPathVariable( @PathVariable String name , @PathVariable String gender ) {          if ( gender . equalsIgnoreCase ( "m" )) {                  return new HelloWorldBean(String. format ( "Hello Mr %s" , name ));          } else if ( gender . equalsIgnoreCase ( "f" )) {                  return new HelloWorldBean(String. format ( "Hello Mrs %s" , name ));          }  ...

Step 1 Rest With Spring Boot

Image
How to Build Rest API  Identify Resources: (/user, /user/{id})  etc.  Identify Actions (GET, POST, PUT, DELETE, PATCH etc.)  Defining Request and Response Structure  Define  Response Status( 200 as Ok, 404 as Page Not Found, 500 Internal Server Error)     400 Series Errors:  Client Side Error     500 Series Errors:  Server Side Error  Best Practices for Rest API 1.Thinking on Consumer Perspective 2. validation  3  Internationalizations -i18n 4. Exception Handling 5. HATEOAS 6. Versioning 7. Documentation  8. Content Negotiation etc.  Internal Working of Spring Boot 1.   How to Handle Request in Spring Boot? Dispatcher Servlet- Front Controller Pattern Mapping Servlets: dispatcher Servlet urls=[/]  ( as dispatcher servlet is mapped to the [/] root URL)   If you search for Mapping servlets you will find out the given below string in logs which is telling to you dispatcher servlet is ma...

Introduction of RESTful Web Service

Image
Rest Web Service It Stands for Representational State Transfer who coined Rest ?  Roy Fielding, who is developed HTTP as well Rest is make Best use of HTTP: Key Abstraction - Resources: 1. A Resource has an URI (Uniform Resource Identifier)     /user/Khan/todos/1     /user/Khan/todos     /user/Khan Note: It shows we  assign a URI to Each Resource           Rest does not worry about how you are representing your  resource            is it JSON,XML or HTML 2. A Resource can have different representations     JSON     XML     HTML Methods for Resources: 1. Create Resource   : POST 2. Update Resource  : PUT 3. Get Resource        : GET 4. Delete Resource   : DELETE REST Data Exchange Format No Restriction.(But JSON format is popular in restful) Transport Only HTTP (Restricted) Service Definition No Standard (but Swagg...