Table of contents
1.
Introduction ⛳
2.
Enhancing Swagger Documentation with Custom Annotations📝
3.
Monitoring APIs with Spring Boot Actuator🙋
3.1.
📌Spring Boot Actuator 
3.2.
📌Spring Data Rest HAL Browser
4.
Implementing Static Filtering for RESTful Services🧑‍💻
4.1.
📌@JsonIgnore
4.2.
📌 @JsonIgnoreProperties 
5.
Implementing Dynamic Filtering for RESTful Services🌀
6.
Versioning RESTful Web Services-Basic Approach With URIs🎯
6.1.
📌 URI Versioning
6.2.
📌 Versioning using Custom Request Header
6.3.
📌 Versioning using Accept Header
7.
Frequently Asked Questions
7.1.
What is Spring Boot?
7.2.
What are the benefits of using Spring Boot for REST API?
7.3.
What is Swagger?
7.4.
What are RESTful Web Services?
7.5.
What are the methods of HTTP?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Implementing Static Filtering for RESTful Services

Author Aashna Luthra
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction ⛳

A REST or RESTful API is an acronym for Representational State Transfer API. It is an architectural style that defines a set of constraints to create web services and is one of the most common choices in terms of public APIs. It uses HTTP to send a request from a client to a server, and the response is received in the form of HTML, XML, JSON (the most popular format), or image.

intro REST


In this blog, we will discuss swagger and RESTful services with Spring Boot. 

Enhancing Swagger Documentation with Custom Annotations📝

Swagger is an open-source tool and builds around OpenAPI Specification. It is helpful for developers to design, develop and use RESTful APIs. Swagger supports JSON and UI, making it one of the most popular API documentation formats for RESTful Services. 

The main Swagger tools are: 

Swagger UI: helps in creating interactive API documentation.

Swagger Editor: browser-based editor to write OpenAPI specifications.

Swagger Codegen: generates client libraries and server stubs(API implementation stub) from OpenAPI specification.  

Let us first generate Swagger documentation for RESTful services. 

STEPS :

▶ Download the Spring Tool Suite(STS) and create a starter project. 

▶ Add the dependencies springfox-swagger2 and springfox-swagger-ui in pom.xml file.

The dependencies are as follows-

<dependency>  
    <groupId>io.springfox</groupId>  
    <artifactId>springfox-swagger2</artifactId>  
    <version>2.9.2</version>  
</dependency>  

<dependency>  
    <groupId>io.springfox</groupId>  
    <artifactId>springfox-swagger-ui</artifactId>  
    <version>2.9.2</version>  
</dependency> 

▶ Now, create a class with the name ConfigureSwagger.java and write the following code :

package com.example.demo;  
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  
import springfox.documentation.spi.DocumentationType;  
import springfox.documentation.spring.web.plugins.Docket;  
import springfox.documentation.swagger2.annotations.EnableSwagger2; 

@Configuration  
//Enable Swagger  
@EnableSwagger2  
public class SwaggerConfig   
{  
    //creating bean  
    @Bean  
    public Docket api()  
    {  
        //creating constructor of Docket class that accepts parameter DocumentationType  
        return new Docket(DocumentationType.SWAGGER_2);  
    }  
} 
You can also try this code with Online Java Compiler
Run Code


▶ Run the application and open the browser having URI as http://localhost:8080/v2/api-docs

The above link will show a JSON format Swagger documentation.

Here are the main steps for Enhancing Swagger Documentation

STEPS:

▶  In the ConfigureSwagger.java file, make a constant DEFAULT_API of type ApiInfo.

private static final ApiInfo DEFAULT_API = null;

▶  Hold the ctrl key and then click on ApiInfo, which will open the ApiInfo class. The ApiInfo class will look like this : 

configure swagger

▶  Copy the constants DEFAULT_CONTACT and DEFAULT as in the class ApiInfo and paste them into the ConfigureSwagger.java class. Rename the constant DEFAULT to DEFAULT_API. 

▶  Configure the DEFAULT_API and contact details(DEFAULT_CONTACT ) of the developer or organization.

The final ConfigureSwagger will look like this

 

package com.example.demo;
import java.util.ArrayList;  
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  
import springfox.documentation.spi.DocumentationType;  
import springfox.documentation.spring.web.plugins.Docket;  
import springfox.documentation.swagger2.annotations.EnableSwagger2;  
import springfox.documentation.service.ApiInfo;  
import springfox.documentation.service.Contact;  
import springfox.documentation.service.VendorExtension;  

@Configuration  
//Enable Swagger  
@EnableSwagger2  
public class ConfigureSwagger {
   public static final Contact DEFAULT_CONTACT = new Contact("Ninja", "https://www.codingninjas.com/", "example@codingninjas.com");  
   public static final ApiInfo DEFAULT_API = new ApiInfo("Example RESTful Api", "Api Documentation", "1.0", "urn:tos", DEFAULT_CONTACT, "Apache        2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList<VendorExtension>());
   @Bean  
   public Docket api()  
   { 
       ApiInfo apiInfo;  
       //creating constructor of Docket class that accepts parameter DocumentationType  
       return new Docket(DocumentationType.SWAGGER_2).apiInfo(DEFAULT_API);  
   }  
}
You can also try this code with Online Java Compiler
Run Code

▶  Restart the application, and in the browser,  go to the URI http://localhost:8080/v2/api-docs. It will show the updated API and contact detail in  the Swagger documentation

enahnce swagger

Monitoring APIs with Spring Boot Actuator🙋

Spring Boot is a tool that has HTTP endpoints and provides the actuator to manage and monitor applications. Monitoring is essential, especially while building microservices. 

For adding the monitoring service in a spring boot project, two dependencies are needed:

📌Spring Boot Actuator 

If the working of a service goes down or fails, the spring boot actuator helps in this case as it provides production-ready features. 

📌Spring Data Rest HAL Browser

Hypertext Application Language (HAL) helps export APIs quickly and gives a way to hyperlink between resources in API. HAL browser identifies the links and displays the links on the screen so browsing through the API can be done easily. 

Implementing Static Filtering for RESTful Services🧑‍💻

Filters are provided by the JAX-RS framework. They can be applied on- a request to a resource or a response from a resource. There are two annotations provided by Jackson which are used in filtering- @JsonIgnore and @JsonIgnoreProperties. 

📌@JsonIgnore

In this, the properties that are to be excluded are marked one by one. It is a method level annotation. To create a filter, perform the following steps:

STEPS:

▶ Create a new package with the name com.codingninjas.main.filtering, and in the package, create a Controller class named FilterController.java. 

▶ Create a bean with the name as ExampleBean.

package com.codingninjas.main.filtering;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RestController;
  
@RestController  
public class FilterController   
{   
   @RequestMapping("/filtering")  
   public ExampleBean retrieveSomeBean()  
   {  
       return new ExampleBean("Ninja", “10”, "50");     
   }  
}
You can also try this code with Online Java Compiler
Run Code

▶ Create a class with the name ExampleBean.java and define three private attributes: name, roll, and marks

▶ Generate Constructors, Getters, and Setters. After this step, ExampleBean.java will look like this:

package com.codingninjas.main.filtering;  
import com.fasterxml.jackson.annotation.JsonIgnore;  

public class ExampleBean   
{  
   private  String name;  
   private  String roll;  
   //@JsonIgnore indicates that the annotated method or field is to be ignored  
   @JsonIgnore  
   private  String marks;  
   //generating constructor  
   public SomeBean(String name, String roll, String marks)   
   {  
       super();  
       this.name = name;  
       this.roll = roll;  
       this.marks = marks;  
   }  
   public String getName()   
   {  
       return name;  
   }  
   public void setName(String name)  
   {  
       this.name = name;  
   }  
   public String getRoll()   
   {  
       return roll;     
   }  
   public void setRoll(String roll)   
   {  
       this.roll = roll;     
   }  
   public String getMarks()   
   {  
       return marks;    
   }  
   public void setMarks(String marks)   
   {  
       this.marks = marks;  
   }  
}
You can also try this code with Online Java Compiler
Run Code

▶ Open Postman and send the GET request as http://localhost:8080/filtering. It will return two fields as : name and roll.  Since the field marks was annotated as @JsonIgnore, it will not be displayed in the output.

filtering
output filtering

▶ Create another beam that returns a list of ExampleBean

The FilterController.java will look like this : 

package com.codingninjas.main.filtering;
import java.util.Arrays;  
import java.util.List;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.RestController;  
@RestController  

public class ControllerFiltering {
   @GetMapping(path="/filtering")  
   public ExampleBean retrieveSomeBean()  
   {  
       return new ExampleBean("Ninja", "10","50");   
   }
   @GetMapping(path="/filtering-list") 
   public List<ExampleBean> retrieveListOfExampleBeans()  
   {  
       return Arrays.asList(new ExampleBean("Ninja_1", "20","60"), new ExampleBean("Ninja_2", "21","80"));   
   }
}
You can also try this code with Online Java Compiler
Run Code

▶ Open Postman and send the GET request as http://localhost:8080/filtering-list. It will return two fields: name and roll.  Since the field “marks” field was annotated as @JsonIgnore, it will not be displayed in the output. 

filtering list
output filtering list

📌 @JsonIgnoreProperties 

The primary function of @JsonIgnoreProperties is to ignore the logical properties in JSON serialization and deserialization. It is a class-level annotation. In this example, we want to ignore the properties name and roll in the response. These are the properties which will be taking part in JSON serialization and deserialization.  

The logical properties considered to be ignored in JSON serialization and deserialization are the properties ignored by @JsonIgnore and @JsonIgnoreProperties.

package com.codingninjas.main.filtering;  
import com.fasterxml.jackson.annotation.JsonIgnore;  

@JsonIgnoreProperties({“name”})
public class ExampleBean   
{  
   private  String name;  
   private  String roll;  
   //@JsonIgnore indicates that the annotated method or field is to be ignored  
   @JsonIgnore  
   private  String marks;  
   //generating constructor  
   public SomeBean(String name, String roll, String marks)   
   {  
       super();  
       this.name = name;  
       this.roll = roll;  
       this.marks = marks;  
   }  
   public String getName()   
   {  
       return name;  
   }  
   public void setName(String name)  
   {  
       this.name = name;  
   }  
   public String getRoll()   
   {  
       return roll;     
   }  
   public void setRoll(String roll)   
   {  
       this.roll = roll;     
   }  
   public String getMarks()   
   {  
       return marks;    
   }  
   public void setMarks(String marks)   
   {  
       this.marks = marks;  
   }  
}
You can also try this code with Online Java Compiler
Run Code

The following output can be seen when a GET request is made in Postman. 

jsonpropignore

Only “roll” field properties are displayed in output as the field “name” is specified in @JsonIgnoreProperties, and the property “marks” is annotated with @JsonIgnore. 

Whatever we have done till now comes under the topic Static Filtering. 

Implementing Dynamic Filtering for RESTful Services🌀

Compared to static filtering, different filters are defined for different services in dynamic filtering. Let’s consider the example we have used which have the fields as: nameroll, and marks

We wish to send two fields: name and roll for the first service and name and marks for the second service. For this reason, the concept of dynamic filtering comes into picture. To implement this, the MappingJacksonValue class is used. 

But we do face a limitation here. Dynamic filtering cannot be directly configured in the bean. 

Versioning RESTful Web Services-Basic Approach With URIs🎯

It is always suggested to version the Web API. When changes are identified, versioning helps in iterating faster. The primary significance of versioning comes into picture when some users want to add more functionality to the Web API but also want to keep the existing functionality. Some users might want to use the old API, and others want to use the new API version. 

There are mainly three approaches to version: 

📌 URI Versioning

Twitter uses this versioning, and it is specified in the URL as a query string. This type of versioning is relatively straightforward. 

📌 Versioning using Custom Request Header

Microsoft uses this versioning, and a custom header allows the user to preserve the URLs. There is no need to change the URL as version information is specified in the request header. Moreover, the user cannot access this versioning in the standard browser, such as Chrome or Mozilla; special plugins are needed in this case.  

📌 Versioning using Accept Header

Github uses this versioning, and the accept header defines the character encodings and media type. It is also known as media type versioningaccept header or content negotiation. The version information through accept headers can be passed without changing the URL. Moreover, the user cannot access this versioning in the standard browser, such as Chrome or Mozilla; special plugins are needed in this case.  

We hope you have understood everything about implementing static filtering for RESTful services. 🙌

Frequently Asked Questions

What is Spring Boot?

Spring boot is an open-source java framework for developing web applications and microservices. 

What are the benefits of using Spring Boot for REST API?

Spring boot allows the creation of REST APIs with no requirement for complex XML configurations. 

What is Swagger?

Swagger is a set of open-source rules and tools built around the OpenAPI specification that helps design, build and consume REST APIs. 

What are RESTful Web Services?

REST stands for REpresentational State Transfer. The main objective of RESTful services is to make web services more effective.

What are the methods of HTTP?

GET, PUT, POST, and DELETE. 

Conclusion

In this blog, we studied Swagger documentation, implementing static filtering for REST and other concepts. We also explored spring boot  and dynamic filtering for RESTful services. At last, we discussed versioning REST web services with URIs. You can refer to similar articles for further information.

  1. What is a web service?
  2. RESTful statelessness
  3. Web service components
  4. RESTful environment setup


Happy Learning Ninja! 🥷

Live masterclass