Python request resulting in blank response

11,837

What API are you connecting to?

Try adding a user-agent to the header:

r = requests.get(url, auth=HTTPBasicAuth(apiuser, apipass), headers={'User-Agent':'test'})
Share:
11,837

Related videos on Youtube

MrG
Author by

MrG

Data Geek

Updated on June 04, 2022

Comments

  • MrG
    MrG almost 2 years

    I'm relatively new to Python so would like some help, I've created a script which simply use the request library and basic auth to connect to an API and returns the xml or Json result.

    # Imports
    import requests
    from requests.auth import HTTPBasicAuth
    
    # Set variables 
    url = "api"
    apiuser = 'test'
    apipass = 'testpass'
    
    # CALL API
    r = requests.get(url, auth=HTTPBasicAuth(apiuser, apipass))
    
    # Print Statuscode
    print(r.status_code)
    
    # Print XML
    xmlString = str(r.text)
    print(xmlString)
    

    if but it returns a blank string.

    If I was to use a browser to call the api and enter the cretentials I get the following response.

    <Response>
    <status>SUCCESS</status>
    <callId>99999903219032190321</callId>
    <result xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Dummy">
    <authorFullName>jack jones</authorFullName>
    <authorOrderNumber>1</authorOrderNumber>
    </result>
    </Response>
    

    Can anyone tell me where I'm going wrong.

    • SuperStew
      SuperStew about 6 years
      Are you sure you need HTTPBasicAuth?
    • IMCoins
      IMCoins about 6 years
      What does print(r.status_code) outputs ? Have you tried print r.content ?
    • MrG
      MrG about 6 years
      the status code is 200 which is what I'm finding confusing and if I print the r.content it returns b''.....its version 3 so print r.content doesn't work so I use print(r.content) if thats correct
  • MrG
    MrG about 6 years
    Sorry i'd printed the r.status_code to see what was being returned to see if there was anything else which was causing the error. I've tried the time.sleep option and it not worked sadly, I'm confused as it returned data to a web browser quite quickly 1 second max. but the calling the data via python results in nothing .
  • ipop
    ipop about 6 years
    print(r.content) also returns blank? could you provide the API you are using if it's a public one?
  • MrG
    MrG about 6 years
    Thanks guys, I've sorted the issue not, it was down to the auth type, it required digest auth after all # CALL API r = requests.get(url, auth=HTTPDigestAuth(apiuser, apipass))