Search code examples
apixmlhttprequestusps

USPS Address Validation API using XML and Javascript


I ran the following code (with my user Id entered):

const xhttp = new XMLHttpRequest();
const url = 'https://secure.shippingapis.com/ShippingAPI.dll?API=Verify';
xhttp.open('GET', url, true);

xhttp.onreadystatechange = (e) => {
  if (xhttp.readyState == 4 && xhttp.status == 200) {
    console.log('request successful');
    console.log(xhttp.responseXML);
  }
}

let xml = '<AddressValidateRequest USERID="XXXXXXXXXXXX"><Address><Address1>324 Church St</Address1><Address2></Address2><City>Ray</City><State>ND</State><Zip5>58849</Zip5><Zip4></Zip4></Address></AddressValidateRequest>'

xhttp.send(xml);

This is the response:

<Error>
  <Number>80040B19</Number>
  <Description>XML Syntax Error: Please check the XML request to see if it can be parsed.</Description>
  <Source>USPSCOM::DoAuth</Source>
</Error>

I'm not sure what I'm doing wrong. Is my XML proper? Am I sending it correctly?

Resource: USPS Web Tools API Portal


Solution

  • It looks like you are passing the XML in the body. According to the USPS Web Tools documentation, the XML payload is passed as a query parameter.

    I've refactored you example below.

    const xhttp = new XMLHttpRequest();
    let xml = '<AddressValidateRequest USERID="XXXXXXX"><Address><Address1>324 Church St</Address1><Address2></Address2><City>Ray</City><State>ND</State><Zip5>58849</Zip5><Zip4></Zip4></Address></AddressValidateRequest>'
    const url = 'https://secure.shippingapis.com/ShippingAPI.dll?API=Verify&xml=' + xml;
    xhttp.open('GET', url, true);
    
    xhttp.onreadystatechange = (e) => {
      if (xhttp.readyState == 4 && xhttp.status == 200) {
        console.log('request successful');
        console.log(xhttp.responseXML);
      }
    }
    
    xhttp.send();
    

    Checkout our community project where we've created modern USPS Web Tools API documentation