Home > Enterprise >  How to make multiple @Path in a @GET in JAX-RS API?
How to make multiple @Path in a @GET in JAX-RS API?

Time:09-30

So, in my Resource class I have the following:

@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Carta> get() {
    return repositorio.getAll();
}

@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Carta getById(@PathParam("id") int id) {
    return repositorio.getID(id);
}

both works, one is a general get (will get all) and the other get by ID. I need to add a third get by String but I'm failing with the @params. I need to add this to the Resource class:

@GET
@Path("{nome}")
@Produces(MediaType.APPLICATION_JSON)
public List<Carta> getNome(@PathParam("nome") String nome) {
    return repositorio.getString(nome);
}

if I comment the getById lines, my getByString works, the code is good, i just need to make both function at the same time, if it receives a number, it looks for an ID, if its a String it looks into name and description. Also, I wonder if it's better code practice to create more endpoints? Like /search/byid/xx and /search/byname/xxx instead of a general /search/xxx? Thanks.

CodePudding user response:

Rather than creating a different endpoint, you should enhance List<Carta> get() to support filtering by card name.

The expected way to do that is to use the @QueryParam annotation like this:

@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Carta> get(@QueryParam("name") String name) {
    return repositorio.getCartas(name);
}

In the case of null name parameter, all Carta instances will be returned.

  • Related