Posts

Showing posts from July, 2023

Implementing Static Filtering for Rest API

Image
  Customize Rest Api Responses - Filtering and More.. Serialization: convert object into stream (Example JSON) Example we are Return like we are getting back EntityModel in below method public EntityModel<User> getUsers() {} we are getting back List of User in below method public List<User> getAllUsers() {} Converting into a Json or to an XML is what is called serialization Most Popular JSON serialization in Java Is Jackson How About customize the REST Api response returned by Jackson Framewor 1: Customize Field name in response @JSONProperty Value ("") indicates that the name of field (or, derived nameof an accessor method (setter / getter)) is to be used as the property name without any modifications; a non-empty valuecan be used to specify a different name.Property name refers to the name used externally, as the propertyname in JSON objects (as opposed to internal name of field inJava Object) public class User { private Integer id ; @Size (min = 2, messa...

HATEOAS (hypertext as the engine of application state)

Image
 HATEOAS (HyperMedia as the engine of application state) in any web application you see See Data Perform Action (using Links) How to Implement this Action Links (Options) Custom format and Implementation Difficult to maintain (need to create structure in pojo) Use Standard Implementation HAL (JSON Hypertext Application Language) : This is simple format that gives a consistent and easy way to hyperlink between resources in your API This will define how to Link other resources in the REST API STEP 1: add given below dependancy in pom.xml < dependency >      < groupId > org.springframework.boot</ groupId > < artifactId >spring-boot-starter-hateoas</ artifactId > </ dependency > Step 2: import org.springframework.hateoas.EntityModel; @RestController public class UserResourceController { private UserDaoService userDaoService ; //http://localhost:8080/users //EntityModel //WebMvcLinkBuilder @GetMapping ( "/users/{...

4.Versioning Rest API using Media Type Versioning

Image
    4. Media Type Versioning aka Content Negotiation or accept Header SAME-URL Produces= SAME-URL Produces=application/vnd.company.app-v2+json Step 1: VersioningPersonController.java public class VersioningPersonController { @GetMapping (path= "/person/accept" , produces= "application/vnd.company.app-v1+json" ) public Personv1 getFirstVersionOfAcceptHeader() { return new Personv1( "sharuk Khan" ); } @GetMapping (path= "/person/accept" , produces= "application/vnd.company.app-v2+json" ) public Personv2 getSecondVersionOfAcceptHeader() { return new Personv2( new Name( "sharuk" , "Khan" )); } } in Header add accept = application/vnd.company.app-v1+json in Header add accept = application/vnd.company.app-v1+json

3 Versionning Rest API Using Header Versioning

Image
  3. Header Versioning SAME-URL headers=[X-API-VERSION=1] SAME-URL headers=[X-API-VERSION=2] Step 1: VersioningPersonController.jav a public class VersioningPersonController { @GetMapping (path= "/person/header" , headers= "X-API-VERSION=1" ) public Personv1 getFirstVersionOfPersonHeader() { return new Personv1( "salman Khan" ); } @GetMapping (path= "/person/header" , headers= "X-API-VERSION=2" ) public Personv2 getSecondVersionOfPersonHeader() { return new Personv2( new Name( "salman" , "Khan" )); } } Need to add Header to get First version X-API-VERSION = 1 Need to add Header to get second version X-API-VERSION = 2

2 Versionning Rest API Using Request Parameter Versioning

Image
  2 .Request Parameter Versioning      http://localhost:8080/person?version=1     http://localhost:8080/person?version=2 Step 1: VersioningPersonController.java public class VersioningPersonController { @GetMapping (path= "/person" , params= "version=1" ) public Personv1 getFirstVersionOfPersonRequestParameter() { return new Personv1( "Irfan pathan" ); } @GetMapping (path= "/person" , params= "version=2" ) public Personv2 getSecondVersionOfPersonRequestParameter () { return new Personv2( new Name( "Irfan" , "Khan" )); } } with http://localhost:8080/person?version=1 with http://localhost:8080/person?version=2

1 Versioning Rest Api URI

Image
 Versioning Rest Api: Suppose you have built an great Rest API You have 100s of cutomers Now you need to implemnt a breaking change Example: spltit the name into two firstName and LastName with Api localhost:8080/v1/person {     name: "irfan khan" } with Api localhost:8080/v2/person {     "name"; {                firstName: "irfan",                 lastName: "Khan"     } } So in given above examples you can see with two different Response , so we can not directly implement this change into production in first api itself other wise it will hit to the other list of consumer who would want response in single name instead of split name in firstname and lastName, than all you consumer will impacted. Solution : of given above problem is Versioning Rest API So There are number of ways to implements versioning: 1. Url 2. Request Parameter 3. Header 4. Media Type...

Spring Boot Internationalization i18n

Image
 Spring Boot Internationalization i18n: Rest Api sometimes need to write for different Language readers at that time internationalization is requiered ( internationalization has 18 charecters so that by they use i18n ) We will be use of its a HTTP Request Header - Accept Language  Header  Accept-Language: indicate natural Language and local that the customer prefers Example: en - English (Good Morning) Example: nl -  Dutch (Goedemorgen) Example: fr - French (Bonjour) etc HelloWorldController.java @RestController public class HelloWorldController { private MessageSource messageSource ; public HelloWorldController(MessageSource messageSource ) { this . messageSource = messageSource ; } @GetMapping (path= "/hello-world-i18n" ) public String helloWorldi18n() { //this will provide which language is to pick as its pick from request header Locale locale = LocaleContextHolder. getLocale (); String message = messageSource .getMessage( "good.morning....

Content Negotiation in Spring Boot

Image
 Content Negatiation: Same Resource - Same URI with Same URI we can have different Representations are possible we might get Response in JSON format  some other consumer might expect that response in XML formate in given below example we have same response just the difference is JSON and XML formate  so one consumer can get in xml or other one can get response in json formate Example 1 Different Content Type - XML or JSON or ... Example 2 Different Language - English or Hindi or Urdu ... Actually your consumer has to tell us which representation they want from us Q: How can a customer tell the rest api provider what they want as response? Answer: Content Negotiation Example 1 : A consumer can use things like Accept Header , i can sent a request , with  a mime type of application XML . so i can create accept Header with value application xml Example 2 : Another Example is to make use of the Accept Language Header(en, nl,fr, hi,ur,...) so with the same resource we ca...

Configuration Auto Generation of Swagger Documentation

Image
 Rest API Documentation - Swagger and Open API 2011 : Swagger Specification  and tool were Introduces 2016 : Open API Specification Created based on Swagger Specification But Still Swagger tool was exists OpenAPI Specification : this was earlier known as Swagger Specification , this is nothing but  a standard language agnostic interface, to define your Rest API, you can see an open api specification in given below screenshot with openApi 3.0.0 version Swagger UI : Visualize and interact with your REST API Note: springdoc-openapi java library helps to automate the genration of API documentation for Spring boot Projects Given below dependancy is use for OpenApi < dependency > < groupId >org.springdoc</ groupId > < artifactId > springdoc-openapi-starter-webmvc-ui </ artifactId > < version >2.1.0</ version > </ dependency > once added given above dependancy you can able to access swagger UI documentation by given below URL ht...

Advance REST Api Features

Documentations Content Negotiation Internationalization - i18n Versioning   HATEOAS Static Filtering Dynamic Filtering Monitoring 1. Documentations: Consumer of your REST API should know : Resources Actions Request/Response Structure (Constraints/Validations) Chalanges: Accuracy : How do you ensure that your documentations is upto date and correct? Consistency : you may have 100s of REST API in an enterpriise how do you ensure all document in consistency? There are two option to Create Documentation: 1 Manually maintain documentation Additional effort to keep it in sync with code 2.Generate the Documentation from Code Rest APi Documentation Using       Swagger and       Open API:

Validation For Rest API

Image
  For Validation need to add dependancy in Pom xml file  < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-validation</ artifactId > </ dependency > also Added jakarta.validation. constraints on User Pojo Class @ Size (min = 2) private String name ; @ Past private LocalDate birthDate ; @ Pattern (regexp = "^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$" ) private String emailID ; Also Add @Valid Annothation in Post request of Resrouse Creation @PostMapping ( "/users" ) public ResponseEntity<User> addUser( @Valid @RequestBody User user ) { User savedUser = userDaoService .save( user ); URI location = ServletUriComponentsBuilder. fromCurrentRequest () .path( "/{id}" ) .buildAndExpand( savedUser .getId()) .toUri(); return ResponseEntity. created ( location ).build(); } For less than 2 size Name OR Future Date OR wrong mail pattern wi...