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

Viewed 53

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

2 Answers

This should work:

let $request-body := "foo=bar&amp;bar=foo"
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>)

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
Related