DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How to Design a CRUD Web Service for Inheritable Entity
  • Spring Boot: How To Use Java Persistence Query Language (JPQL)
  • How a URL Shortening Application Works
  • Avoid Cross-Shard Data Movement in Distributed Databases

Trending

  • FIPS 140-3: The Security Standard That Protects Our Federal Data
  • Scaling DevOps With NGINX Caching: Reducing Latency and Backend Load
  • Beyond Simple Responses: Building Truly Conversational LLM Chatbots
  • Agentic AI for Automated Application Security and Vulnerability Management
  1. DZone
  2. Data Engineering
  3. Data
  4. Design to Support New Query Parameters in GET Call Through Configurations Without Making Code Changes

Design to Support New Query Parameters in GET Call Through Configurations Without Making Code Changes

In this article, I’m discussing query parameters. Query parameter GET call is a set of parameters that are part of the URL.

By 
Hemanth Atluri user avatar
Hemanth Atluri
·
Dec. 02, 22 · Presentation
Likes (1)
Comment
Save
Tweet
Share
11.1K Views

Join the DZone community and get the full member experience.

Join For Free

With this design support, new query parameters will be as easy as adding a new query parameter as a property in the application's configuration file. Implemented this using Spring Boot framework and MongoDB as the backend database. 

HTTP GET is two types of path parameters and query parameters. In this article, I’m discussing query parameters. Query parameter GET call is a set of parameters that are part of the URL. Query parameters are appended in the URL after the HTTP resource with ? symbol and multiple parameters are concatenated by & symbol. 

Implementation Details

The important part of this design is supporting the query parameters as they are referred to in the JSON path. With this, we can simply include the JSON path as the key and values in the Mongo Query. 

From below JSON example, forPerson resourceId for the JSON path is items.forPerson.resourceId. 

JSON
 
{
"_id": UUID('92f4b597-467a-4094-b796-27d1124c2fbd'),
"forName": {
   "firstName": "Hemanth",
   "lastName": "Atluri"
  },
"invoiceNumber": "387373872",
"items":[
  "resourceId": UUID('bad40e6b-4d17-433c-9c56-b61ea5bef06f'),
  "forPerson": {
    "resourceId": "9714a305-a9ec-4a3f-9ba6–93766b2c77b7"
  }
 ] 
}


In the implementation, all the query parameters provided are applied in AND fashion to filter the resources. 

Some of the query parameters have to be supported with exact values, greater than this value, less than this value, and this element exists. To support this, I used keywords from, to, after, before, and exists and added these to request parameters with a delimiter. 

Now let’s see the code to get a better understanding.

Let’s start with the Controller code: Controller class takes the help of RequestParamValidatorAndConvertor and MongoHelper to give a response back to the client. The core logic is in these two classes. Below is the code snippet:

Java
 
@RestController
@RequestMapping("/v1/orders")
public class MongoRestController {

    Logger log = LoggerFactory.getLogger(MongoRestController.class);

    @Autowired
    private RequestParamValidatorAndConvertor requestParamValidatorAndConvertor;

    @Autowired
    private MongoHelper mongoHelper;

    @GetMapping
    public ResponseEntity search(@RequestParam MultiValueMap<String, String> requestParams) {
        log.info(requestParams.toString());
        ResponseEntity responseEntity = null;
        try {
            List<QueryParameter> queryParameters = requestParamValidatorAndConvertor.validateAndConvertToQueryParameters(requestParams);
            List<Order> orders = mongoHelper.getOrders(queryParameters);
            responseEntity = ResponseEntity.status(HttpStatus.OK).body(orders);
        } catch (IllegalArgumentException ex) {
            responseEntity = ResponseEntity.status(HttpStatus.BAD_REQUEST).body("UnSpported Query Parameter");
        }
        return responseEntity;
    }
}


RequestParamValidatorAndConvertor validates the provided query parameter and converts them into a List of CustomCriteria.Below is the code snippet: 

Java
 
public enum MongoOperator {
    IN, EXISTS, LT,LTE,GT,GTE;
}


Java
 
@NoArgsConstructor
@AllArgsConstructor
@Data
public class QueryParameter {
    private String attributeName;
    private String value;
    private MongoOperator mongoOperator;
}


Java
 
@Component
public class RequestParamValidatorAndConvertor {

    @Value("#{'${supportedQueryParamters}'.split(',')}")
    private List<String> supportedQueryParamters;

    public List<QueryParameter> validateAndConvertToQueryParameters(MultiValueMap<String, String> requestParams) {
        List<QueryParameter> queryParameters = new ArrayList<>();

        requestParams.forEach((key, value) -> {
            QueryParameter qp = new QueryParameter();
            if (key.contains(":")) {
                String[] keySplits = key.split(":");
                MongoOperator mongoOperator = null;

                String queryParameter = keySplits[0];
                String queryParamOperator = keySplits[1];

                if (!supportedQueryParamters.contains(queryParameter)) {
                    throw new IllegalArgumentException("Unsupported Query Parameter");
                }
                if (queryParamOperator.endsWith("from")) {
                    mongoOperator = MongoOperator.GTE;
                }
                if (queryParamOperator.endsWith("to")) {
                    mongoOperator = MongoOperator.LTE;
                }
                if (queryParamOperator.endsWith("after")) {
                    mongoOperator = MongoOperator.GT;
                }
                if (queryParamOperator.endsWith("before")) {
                    mongoOperator = MongoOperator.LT;
                }
                if (queryParamOperator.endsWith("exists")) {
                    mongoOperator = MongoOperator.EXISTS;
                }

                qp.setAttributeName(queryParameter);
                qp.setMongoOperator(mongoOperator);

            } else {
                if (!supportedQueryParamters.contains(key)) {
                    throw new IllegalArgumentException("Unsupported Query Parameter");
                }
                qp.setAttributeName(key);
                qp.setMongoOperator(MongoOperator.IN);
            }

            qp.setValue(String.valueOf(value));
            queryParameters.add(qp);
        });
        return queryParameters;
    }
}


MongoHelper class encapsulates the building of the criteria and querying the MongoDB. Below is the code snippet: 

Java
 
@Component
@AllArgsConstructor
public class MongoHelper {

    private MongoCriteriaBuilder mongoCriteriaBuilder;
    private MongoCustomRepository mongoCustomRepository;

    public List<Order> getOrders(List<QueryParameter> queryParameters) {
        Criteria criteria = mongoCriteriaBuilder.build(queryParameters);
        return mongoCustomRepository.findOrders(criteria);
    }
}


MongoCriteriaBuilder takes the QueryParameters for each query parameter; it creates Criteria and chains individual criteria with AND operator.

 
@Component
public class MongoCriteriaBuilder {

    public Criteria build(List<QueryParameter> queryParameters) {
        List<Criteria> criterias = new ArrayList<>();
        queryParameters.forEach(queryParameter -> {
            Criteria criteria = null;
            switch (queryParameter.getMongoOperator()) {
                case EXISTS:
                    criteria = Criteria.where(queryParameter.getAttributeName()).exists(Boolean.getBoolean(queryParameter.getValue()));
                case GT:
                    criteria = Criteria.where(queryParameter.getAttributeName()).gt(queryParameter.getValue());
                case GTE:
                    criteria = Criteria.where(queryParameter.getAttributeName()).gte(queryParameter.getValue());
                case LT:
                    criteria = Criteria.where(queryParameter.getAttributeName()).lt(queryParameter.getValue());
                case LTE:
                    criteria = Criteria.where(queryParameter.getAttributeName()).lte(queryParameter.getValue());
                default:
                    List<String> values = Arrays.stream(queryParameter.getValue().split(",")).collect(Collectors.toList());
                    criteria = Criteria.where(queryParameter.getAttributeName()).in(values);
            }
            criterias.add(criteria);
        });
        Criteria criteria = new Criteria().andOperator(criterias.toArray(new Criteria[criterias.size()]));
        return criteria;
    }
}


MongoCustomRepository build’s the mongo query with the criteria from the MongoCriteriaBuilder and passes it to the MongoTemplate to get the List of documents back. 

Java
 
@Component
@AllArgsConstructor
public class MongoCustomRepository {

    private MongoTemplate mongoTemplate;

    public List<Order> findOrders(Criteria criteria){
        Query query = new Query();
        query.addCriteria(criteria);
        return mongoTemplate.find(query, Order.class);
    }
}


Conclusion 

With the above implementation, new query parameters can be supported through configurations. This article shares only the talks about querying; this doesn’t include the performance of the query. To achieve performance in the query, one must index the field and understand MongoDB indexing.

Design Data Types Database Query language Spring Framework

Opinions expressed by DZone contributors are their own.

Related

  • How to Design a CRUD Web Service for Inheritable Entity
  • Spring Boot: How To Use Java Persistence Query Language (JPQL)
  • How a URL Shortening Application Works
  • Avoid Cross-Shard Data Movement in Distributed Databases

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!