1

I'm trying to retrieve data from a database to an mobile app through a REST web service. I've managed to make some basic functions but when I try to add functions I run into problems. For example I want to be able to find "Customers" by their Id and their name. When I have two Get methods, one with "/{id}" and one with "/{name}" the app does not know what to use. What can I do to search by name? This is the controller from the web service.

package com.example;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/customers")
public class CustomerController {
private CustomerRepository repository;

@Autowired
public CustomerController(CustomerRepository repository) {
    this.repository = repository;
}

@RequestMapping(value = "/{name}", method = RequestMethod.GET)
public ResponseEntity<Customer> get(@PathVariable("name") String name) {
    Customer customer = repository.findByName(name);
    if (null == customer) {
        return new ResponseEntity<Customer>(HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity<Customer>(customer, HttpStatus.OK);
}

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<Customer> get(@PathVariable("id") Long id) {
    Customer customer = repository.findOne(id);
    if (null == customer) {
        return new ResponseEntity<Customer>(HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity<Customer>(customer, HttpStatus.OK);*
}

@RequestMapping(value = "/new", method = RequestMethod.POST)
public ResponseEntity<Customer> update(@RequestBody Customer customer) {
    repository.save(customer);
    return get(customer.getName());
}

@RequestMapping
public List<Customer> all() {
    return repository.findAll();
}
}

This is the service from the android application

package com.ermehtar.poppins;

import java.util.List;

import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.PATCH;
import retrofit2.http.POST;
import retrofit2.http.Path;

public interface CustomerService {
@GET("customers")
Call<List<Customer>> all();

@GET("customers/{id}")
Call<Customer> getUser(@Path("id") Long id);

@GET("customers/{name}")
Call<Customer> getUser(@Path("name") String name);

@POST("customers/new")
Call<Customer> create(@Body Customer customer);
}

Then this is the function that I use to call the service by name. The response.body will be null when both /name and /id functions are in the web service controller but when one of them is commented out this works just fine.

findUsernameButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Call<Customer> createCall = service.getUser("John");
            createCall.enqueue(new Callback<Customer>() {
                @Override
                public void onResponse(Call<Customer> _, Response<Customer> resp) {
                    findUsernameButton.setText(resp.body().name);
                }

                @Override
                public void onFailure(Call<Customer> _, Throwable t) {
                    t.printStackTrace();
                    allCustomers.setText(t.getMessage());
                }
            });
        }
    });

Hope I've made myself understandable. Please ask if there is something unclear or you need more information.

4 Answers 4

6

Your restful design can improve. I suggest defining something like this:

New:

/customers/new

This is not correct, in restful a resource creation should be defined by method type. I suggest this:

/customers with POST method.

Search by ID:

/customers/{id}

This is correct, in restful a resource should be access by id using path variable.

Search by name:

/customers/{name}

This is not correct, here you are querying the customers resource, so, you should use query params, I suggest this:

/customers?name=<<name>>

If you have multiple query methods, you will get a conflict because you cannot have more than one GET method in a controller with the same path. So, you can modify @RequestMapping to explicit assert which query params are required like this:

@RequestMapping(value = "/", method = RequestMethod.GET, , params = "name")
public ResponseEntity<Customer> getByName(@RequestParam("name") String name) {
    ...
}

@RequestMapping(value = "/", method = RequestMethod.GET, , params = "lastname")
public ResponseEntity<Customer> getByLastname(@RequestParam("lastname") String lastname) {
    ...
}
0
0

Differentiate the URLs with a different path which will also make them more RESTful.

Search by name:

/customers/names/{name}

Search by ID:

/customers/ids/{id}

In the future you might want to add another search, perhaps by city:

/customers/cities/{city}
0
0

Your controller has ambiguous handler methods mapped so when calling the endpoint you will actually get an exception. Fix this by creating different mappings for get by id and get by name.

0

Resource is uniquely identified by its PATH (and not by it's params). So, there're few resources with the same PATH: "customers/"

You can create two different resources like:

  • @RequestMapping(value = "/id", method = RequestMethod.GET)
  • @RequestMapping(value = "/name", method = RequestMethod.GET)

Or you can make one resource with many request parameters: @RequestMapping(value = "/get", method = RequestMethod.GET) public ResponseEntity<Customer> get(@RequestParam ("id") Long id, @RequestParam ("name") String name)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.