Wednesday, 7 August 2019

Spring boot REST: How to return specific fields of an entity


If my uri is like '{PATH}?filter=country,firstName,lastName', then the API should return country, firstName and lastName fields.

If my uri is like '{PATH}?filter=id,firstName', then the API should return id and firstName fields.

We can solve this by parsing the filter and populating respective data in a map.

Example
@RequestMapping("/employees/{id}")
public ResponseEntity<Map<String, Object>> welcomeMe(@RequestParam(name = "filter") String filter,
        @PathVariable (value = "id") int id) {
    return ResponseEntity.ok(empRepo.filterData(filter, id));
}

public Map<String, Object> filterData(String filter, int id) {

    if (filter == null)
        return Collections.EMPTY_MAP;

    Employee emp = byId(id);
    if (emp == null)
        return Collections.EMPTY_MAP;

    Map<String, Object> map = new HashMap<>();

    String[] fields = filter.split(",");

    for (String field : fields) {
        if (field.equalsIgnoreCase("id")) {
            map.put("id", emp.getId());
        }

        if (field.equalsIgnoreCase("firstName")) {
            map.put("firstName", emp.getFirstName());
        }

        if (field.equalsIgnoreCase("lastName")) {
            map.put("lastName", emp.getLastName());
        }

        if (field.equalsIgnoreCase("country")) {
            map.put("country", emp.getCountry());
        }

    }

    return map;

}

Find the below working example.


App.java
package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
    public static void main(String[] args) {

        SpringApplication.run(App.class, args);

    }
}


HomeController.java
package com.sample.app.cotroller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.sample.app.repository.EmployeeRepository;

@RestController
public class HomeController {

    @Autowired
    EmployeeRepository empRepo;

    @RequestMapping("/")
    public String home() {
        return "Welcome to spring boot REST App development";
    }

    @RequestMapping("/employees/{id}")
    public ResponseEntity<Map<String, Object>> welcomeMe(@RequestParam(name = "filter") String filter,
            @PathVariable (value = "id") int id) {
        return ResponseEntity.ok(empRepo.filterData(filter, id));
    }

}


Employee.java
package com.sample.app.model;

public class Employee {
    private int id;
    private String firstName;
    private String lastName;
    private String country;

    public Employee(int id, String firstName, String lastName, String country) {
        super();
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.country = country;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

}


EmployeeRepository.java
package com.sample.app.repository;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.sample.app.model.Employee;

@Repository
public class EmployeeRepository {

    private static final List<Employee> emps = new ArrayList<>();

    static {
        Employee emp1 = new Employee(1, "Sunil", "Dayanand", "India");
        Employee emp2 = new Employee(2, "Keerthi", "Shetty", "India");
        Employee emp3 = new Employee(3, "Ram", "Anand", "United States Of America");

        emps.add(emp1);
        emps.add(emp2);
        emps.add(emp3);

    }

    public List<Employee> all() {
        return emps;
    }

    public Map<String, Object> filterData(String filter, int id) {

        if (filter == null)
            return Collections.EMPTY_MAP;

        Employee emp = byId(id);
        if (emp == null)
            return Collections.EMPTY_MAP;

        Map<String, Object> map = new HashMap<>();

        String[] fields = filter.split(",");

        for (String field : fields) {
            if (field.equalsIgnoreCase("id")) {
                map.put("id", emp.getId());
            }

            if (field.equalsIgnoreCase("firstName")) {
                map.put("firstName", emp.getFirstName());
            }

            if (field.equalsIgnoreCase("lastName")) {
                map.put("lastName", emp.getLastName());
            }

            if (field.equalsIgnoreCase("country")) {
                map.put("country", emp.getCountry());
            }

        }

        return map;

    }

    private static Employee byId(int id) {
        for (Employee emp : emps) {
            if (id == emp.getId()) {
                return emp;
            }
        }

        return null;
    }
}


pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>springRest</groupId>
    <artifactId>springRest</artifactId>
    <version>1</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
    </parent>

    <name>springbootApp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
</project>


Total project structure looks like below.

Run App.java.

Open the url 'http://localhost:8080/employees/2?filter=id,firstName', you will get below response.

{
  "firstName": "Keerthi",
  "id": 2
}

Open the url 'http://localhost:8080/employees/2?filter=country,firstName,lastName', you will get below response.

{
  "country": "India",
  "firstName": "Keerthi",
  "lastName": "Shetty"
}

You can download complete working application from this link.



Previous                                                    Next                                                    Home

No comments:

Post a Comment