Define path in a get call api rest

1.3k Views Asked by At

I have an api rest about movies. I want to search movies by "name". How I should define the path? Error with the pathParam. It says it cannot resolve it.

@GET
@Path("/search?text=name")
@Produces(MediaType.APPLICATION_JSON)
public Response getMovieByName(@Context HttpServletRequest req, 
@PathParam("name") String name) {
if (!checkLoggedIn(req)) {
    throw new WebApplicationException("User not logged.");
}
    return buildResponse(movieService.getMovieByName(name));
}
2

There are 2 best solutions below

0
ernest_k On

This is query parameter, not a path parameter. You should not include query parameters in your path. They will be given to you when sent by the client:

@Path("/search")

What you need to change is the annotation used to inject the parameter into your method (use @QueryParam):

public Response getMovieByName(@Context HttpServletRequest req, 
       @QueryParam("name") String name)

The name value will be sent in the name parameter if the service is called with something like /search/?name=moviename

2
Bejond On

It's easy if you use spring with annotation

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RequestController {

    @RequestMapping("/search")
    public Movie search(@RequestParam(value="name", defaultValue="hello") String name) {
        // search and return movie
    }
}

RequestController just intercept request and map to right path, liek /search, /add. Implementation usually located in service layer. Then you can inject it easily.

Invoke is simple

http://localhost:8080/search?name=XMan

For more info