0

I have a dropwizard REST API which provides responses in either JSON format or XML format. Right now the client can specify which type of response he needs by specifying it in Accept header field. I have seen some URLs which specify the type in the URL itself like below

www.example.com/foo.json?id=1 will give response in JSON format

and

www.example.com/foo.xml?id=1 will return response in XML format

How can i do this without two different API endpoints?

Manu Viswam
  • 1,606
  • 2
  • 18
  • 33

3 Answers3

1

This is something that Jersey supports (and thus Dropwizard) by configuring the media type mappings. See the question "Jersey: Is there a clean way to specify allowed URL extensions?" question for some details.

To get at the required configuration, in Dropwizard 0.6 in your Service run() method you would do something like:

final ResourceConfig resoureConfig = environment.getJerseyResourceConfig();
final Map<String, MediaType> mediaTypeMappings = resourceConfig.getMediaTypeMappings();
mediaTypeMappings.put("json", MediaType.APPLICATION_JSON_TYPE);        
mediaTypeMappings.put("xml", MediaType.APPLICATION_XML_TYPE);

For Dropwizard 0.7 you access the resource config like this:

final ResourceConfig resourceConfig = environment.jersey().getResourceConfig();
Community
  • 1
  • 1
deverton
  • 401
  • 2
  • 7
0

I think you can specify your API endpoint as foo.* then in your API endpoint you can parse the "extension" and get the requested format.

I based my answer on this: https://blog.apigee.com/detail/restful_api_design_support_multiple_formats/

mavalan
  • 21
  • 2
0

Specify the url like this. @Path("someURI.{format}") Now you can get format in which you need to give the output. Depends on that you can return value with single end point.

Manikandan
  • 3,025
  • 2
  • 19
  • 28
  • In this way i have to hardcode my outputs to the format specified in path parameter. Is there any way to bind it to dropwizard? If the type is specified in accept header, dropwizard will automatically map output to the specified type. – Manu Viswam Feb 05 '14 at 17:59
  • Refer http://stackoverflow.com/questions/11637365/dropwizard-produce-both-html-and-json-from-the-same-class. – Manikandan Feb 06 '14 at 04:22
  • This does'nt solve my problem. I have already done steps to return JSON or XML. Dropwizard automatically reads the accept header and map the output to required type. I need to specify the type in URL instead of accept header. – Manu Viswam Feb 07 '14 at 04:42