Search code examples
jsonxmlxqueryoxygenxml

How to get the necessary data from an API


I need to make a school project in Oxygen, using the following API: https://potterapi.com/ I wrote a function to get all the necessary JSON data from the API:

let $apikey := fn:doc("potterapi.key")/apikey/string() return map { "characters": fn:json-doc("https://www.potterapi.com/v1/characters?key=" || $apikey), "houses": fn:json-doc("https://www.potterapi.com/v1/houses?key=" || $apikey), "spells": fn:json-doc("https://www.potterapi.com/v1/characters?key=" || $apikey) }

I also made an another xml scheme where I define the apikey, and i need to get the data in json format. Can you please help me with this?


Solution

  • To serialize an XQuery 3.1 map as JSON with XQuery 3.1 you have two options, either use the serialize function

    serialize(
      let $apikey := fn:doc("potterapi.key")/apikey/string() return map { "characters": fn:json-doc("https://www.potterapi.com/v1/characters?key=" || $apikey), "houses": fn:json-doc("https://www.potterapi.com/v1/houses?key=" || $apikey), "spells": fn:json-doc("https://www.potterapi.com/v1/characters?key=" || $apikey) },
      map { 'method' : 'json', 'indent' : true() }
    )
    

    or use the needed XQuery option declarations

    declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";
    
    declare option output:method 'json';
    declare option output:indent 'yes';
    
    let $apikey := fn:doc("potterapi.key")/apikey/string() return map { "characters": fn:json-doc("https://www.potterapi.com/v1/characters?key=" || $apikey), "houses": fn:json-doc("https://www.potterapi.com/v1/houses?key=" || $apikey), "spells": fn:json-doc("https://www.potterapi.com/v1/characters?key=" || $apikey) }