2

I am trying to use an API (notably the companieshouse one) and have managed to get it working to the point where I can use the command line to make a request to the API website and have data returned, I do this using the following code:

r = requests.get('https://api.companieshouse.gov.uk/company/**COMPANY NUMBER**/filing-history', auth=('**AUTH CODE**', ''))

r.json()

This works insofar as it spits out the relevant information in the command line interface, however what I really want to do is save that data to my computer, preferably in the .json format. Most solutions I have found online deal with using the requests module to download direct images or webpages from the internet but can't help when it comes to turning text into a file then downloading it.

Hopefully someone here can point me in the right direction and help me out, or worse, tell me its not even possible. Let me know if you need any clarification!

Thanks!!

Ruthus99
  • 492
  • 2
  • 10
  • 25
  • 1
    Your question is "How can I save text into a file in Python?". I'm sure there is more than one example that answers this question here on SO and on countless other websites. – Tomalak Sep 20 '16 at 14:34
  • Hi @Tomalak, I understand that I just didn't fully comprehend that the "r.json" text was not just a placeholder, I thought python forgot about it completely as soon as it was sent to the command line and so could not be retrieved in order to be converted into an actual file. Sorry for the ignorance I'm just new to this :) – Ruthus99 Sep 20 '16 at 14:55

1 Answers1

5

You can make a string out of your JSON like this:

import json
json_str = json.dumps(r.json())

And then save it as a regular text file using standard methods.

with open(filename, 'w') as f:
    f.write(json_str)

EDIT: as pointed out in comments by @Tomalak, this code does double conversion, which is clearly not needed here. So you can just

with open(filename, 'w') as f:
    f.write(r.text)
Pavel Gurkov
  • 737
  • 5
  • 14
  • top quality, works like a charm, thanks a million! – Ruthus99 Sep 20 '16 at 14:52
  • 4
    Pavel: HTTP gives you text. When you call `r.json()`, what this does internally is `json.loads(r.text)`. So what your answer recommends is `json_str = json.dumps(json.loads(r.text))`, which is kind of unnecessary. How about `f.write(t.text)`? – Tomalak Sep 20 '16 at 15:02
  • Right, I'm sorry. It's totally unnecessary. I'll edit the answer. – Pavel Gurkov Sep 21 '16 at 15:10