Search code examples
xquerymarklogic

Making a MarkLogic xdmp:http-post() request with x-www-form-urlencoded request body


How could I send a xdmp:http-post() request that has a x-www-form-urlencoded request body with two key value pairs?

Example request:

let $request-body := <key-value-pairs>
                      <foo>bar</foo>
                      <bar>foo</bar>
                    <key-value-pairs>

return
xdmp:http-post("https://myendpoint.com", 
              <options xmlns="xdmp:http">
                <headers>
                  <Content-type>application/x-www-form-urlencoded</Content-type>
                </headers>
                <data>{$request-body}</data>
              </options>)

This is unfortunately not in the MarkLogic documentation: https://docs.marklogic.com/xdmp:http-post


Solution

  • Rob's answer is correct, but I would suggest calculating the request-body, and applying encode-for-uri properly. Something like:

    let $form-data := <key-value-pairs>
                          <foo>bar</foo>
                          <bar>foo</bar>
                        </key-value-pairs>
    let $request-body := string-join(
      for $pair in $form-data/*
      let $key := name($pair)
      let $val := data($pair)
      return (encode-for-uri($key) || '=' || encode-for-uri($val)),
      '&amp;'
    )
    return $request-body