0

I'm trying to write the output of an API 'get' request to a file. I know the function works as the output of the request is returned successfully and in full in shell.

The function creates the file, but the file only includes the status code for the get request - can anyone help me understand why? Still pretty new to Python and very new to calling APIs...

def user_info(token):
  heads = {"Authorization": "bearer " + token, "Content-type": "application/json"}
  url = "xxxxx"
  request = req.get(url, headers=heads)
  with open('userdata.txt', 'w') as f:
      f.write(str(request))
  if request.status_code == 200:
      return request.json()
  else:
      return "User Info FAILED! Failure code: {}, error: {}".format(request.status_code,request.json()['error'])

The file just contains:

<Response [200]>

Thanks!

3
  • well what do you want to put in the file? if you want to put the json response then f.write(request.json()) Commented Feb 10, 2021 at 17:03
  • aha... f.write(str(request.json())) works, but if I don't specify it should be returned as a string is errors with "TypeError: write() argument must be str, not dict" Commented Feb 10, 2021 at 17:04
  • 1
    @Steve request.json(), not request.json. Commented Feb 10, 2021 at 17:06

1 Answer 1

1

A Response object in the requests module when called as a string will return its status code as detailed in the Response python code

    def __repr__(self):
        return '<Response [%s]>' % (self.status_code)

If you want to write the json from the response as a string then you can use the built in json module and use its dumps method to dump it as a string not a dict.

import requests
import json

with open("myfile.txt", "w") as output:
    resp = requests.get("https://jsonplaceholder.typicode.com/todos/1")
    output.write(json.dumps(resp.json()))
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.