0

I’m working with the USPS APIs which are XMLs. I want to be able to pass variables into the XML tree without rebuilding it child by child. How do I do it in Python?

def fixed_xml_body_as_string(dest_zip, origin_zip):
  
  #pass zip codes into XML

  return """
  https://secure.shippingapis.com/shippingapi.dll?API=RateV4&XML=
  <RateV4Request USERID='XXXXXXXXXXX'>
  <Revision>2</Revision>
  <Package ID="1ST">
  <Service>PRIORITY</Service>
  <ZipOrigination></ZipOrigination>
  <ZipDestination></ZipDestination>
  <Pounds>1</Pounds>
  <Ounces>0</Ounces>
  <Container></Container>
  <Width></Width>
  <Length></Length>
  <Height></Height>
  <Girth></Girth>
  <Machinable>false</Machinable>
  </Package>
  </RateV4Request>
"""

I want to dynamically pass the zip codes into the XML.

1
  • Adding code to the body. USPS has a few APIs to track shipping, get rates..etc. Commented Nov 7, 2020 at 7:28

1 Answer 1

1

Just use string format like the below (Note that your 'xml' is not a valid one)

def fixed_xml_body_as_string(dest_zip, origin_zip):
    # pass zip codes into XML

    return f"""
  https://secure.shippingapis.com/shippingapi.dll?API=RateV4&XML=
  <RateV4Request USERID='XXXXXXXXXXX'>
  <Revision>2</Revision>
  <Package ID="1ST">
  <Service>PRIORITY</Service>
  <ZipOrigination>{origin_zip}</ZipOrigination>
  <ZipDestination>{dest_zip}</ZipDestination>
  <Pounds>1</Pounds>
  <Ounces>0</Ounces>
  <Container></Container>
  <Width></Width>
  <Length></Length>
  <Height></Height>
  <Girth></Girth>
  <Machinable>false</Machinable>
  </Package>
  </RateV4Request>
"""


print(fixed_xml_body_as_string(23, 99))

output

 https://secure.shippingapis.com/shippingapi.dll?API=RateV4&XML=
  <RateV4Request USERID='XXXXXXXXXXX'>
  <Revision>2</Revision>
  <Package ID="1ST">
  <Service>PRIORITY</Service>
  <ZipOrigination>99</ZipOrigination>
  <ZipDestination>23</ZipDestination>
  <Pounds>1</Pounds>
  <Ounces>0</Ounces>
  <Container></Container>
  <Width></Width>
  <Length></Length>
  <Height></Height>
  <Girth></Girth>
  <Machinable>false</Machinable>
  </Package>
  </RateV4Request>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.