5

I'm successfully using Dancer2::Plugin::REST to return JSON from my web server when users access mydomain.com/api/1.json .While retaining this feature, how can I use Dancer2::Plugin2::REST to return XML when users access mydomain.com/api/1.xml ?

My config.yml contains this section:

serializers:
  json: JSON
  yml:  YAML
  yaml: YAML
  dump: Dumper
  xml:  XML

My lib/MyApp/API.pm looks like this:

package MyApp::API;

use Dancer2;

use Dancer2::Plugin::REST;
prepare_serializer_for_format;

get '/1.:format' => sub {
    return { 'temperature' => '10', 'date' => '2019-09-01' };
};

true;

As expected I get the correct JSON snippet when running:

curl -H 'Accept-Type: text/json' https://<mydomain>/api/1.json

But when I run:

curl -H 'Accept-Type: text/xml' https://<mydomain>/api/1.xml

or

curl -H 'Accept-Type: application/xml' https://<mydomain>/api/1.xml

or

curl https://<mydomain>/api/1.xml

I get a server error in response:

Internal Server Error

Reference {"exception" => "Reference {\"date\" => \"2019-09-01\",\"tem...} did not pass type constraint "Str" (in $self->{"content"}) at /usr/local/share/perl/5.26.1/Dancer2/Core/Response.pm line 122
    "Str" is a subtype of "Value"
    Reference {"exception" => "Reference {\"date\" => \"2019-09-01\",\"tem...} did not pass type constraint "Value" (in $self->{"content"})
    "Value" is defined as: (defined($_) and not ref($_))

I expected to get a XML response, not a server error. What am I missing?

user12138447
  • 119
  • 5
  • Try `application/xml` – ikegami Sep 29 '19 at 13:36
  • Thanks ikegami, but unfortunately curl -H 'Accept-Type: application/xml' https:///api/1.xml changes nothing, the exact same server error is returned. – user12138447 Sep 29 '19 at 13:47
  • I've now updated my question to reflect this. – user12138447 Sep 29 '19 at 13:56
  • 1
    By the way, do you realize that this will use XML::Simple, [a module you should avoid](https://stackoverflow.com/q/33267765/589924) because it's insanely hard to use the data structures or XML is returns? – ikegami Sep 29 '19 at 14:22
  • 2
    I've been looking into this for a while, and I've come to the conclusion that the list of extensions is hardcoded to `yaml`, `yml`, `json`, `dump`. – ikegami Sep 29 '19 at 15:08
  • @ikegami: Thanks for looking into this. I guess XML is less popular than it used to be. I'll have to generate my XML responses in some other way. – user12138447 Sep 29 '19 at 16:53

0 Answers0