Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i have the same path for two classes in Rest Api?

Is it possible to define same path for two classes?

@Path("/resource")    
public class ResourceA{
..
..
}

@Path("/resource")
public class ResourceB(){
..
..
}
like image 302
Fariba Avatar asked Jan 08 '23 00:01

Fariba


1 Answers

It is possible. See the JAX-RS Spec 3.7.2 Request Matching. In layman's terms, the spec states that all matching root resource classes are put into a set, then all the matching methods from those classes are put into a set. Then sorted. So if the resource class level @Paths are the same, they will both be put into the set for further processing

You can easily test this out, as I have done below (with Jersey Test Framework)

public class SamePathTest extends JerseyTest {

    @Test
    public void testSamePaths() {
        String xml = target("resource").request()
                .accept("application/xml").get(String.class);
        assertEquals("XML", xml);
        String json = target("resource").request()
                .accept("application/json").get(String.class);
        assertEquals("JSON", json);
    }

    @Path("resource")
    public static class XmlResource {
        @GET @Produces(MediaType.APPLICATION_XML)
        public String getXml() { return "XML"; }
    }

    @Path("resource")
    public static class JsonResource {
        @GET @Produces(MediaType.APPLICATION_JSON)
        public String getJson() { return "JSON"; }
    }

    @Override
    public Application configure() {
        return new ResourceConfig(XmlResource.class, JsonResource.class);
    }
}
like image 68
Paul Samsotha Avatar answered Jan 24 '23 07:01

Paul Samsotha