pythonipfsinfura

Using IPFS API and Gateway with Infura to Upload Files


I created a private API key in Infura. I was given an API Key, API Key Secret, and an IPFS API Endpoint. I looked at the documentation here. I decided to go the Python route, and I tested it with one file and it seemed successful, but I am never able to see my file in my browser or in my pinned content.

I copied and pasted the code for one file:

import requests

### CREATE AN ARRAY OF TEST FILES ###
files = {
    'file': 'newimages/1.png'
}

### ADD FILE TO IPFS AND SAVE THE HASH ###
response1 = requests.post(endpoint + '/api/v0/add', files=files, auth=(projectId, projectSecret))
print(response1)
hash = response1.text.split(",")[1].split(":")[1].replace('"','')
print(hash)

### READ FILE WITH HASH ###
params = {
    'arg': hash
}
response2 = requests.post(endpoint + '/api/v0/cat', params=params, auth=(projectId, projectSecret))
print(response2)
print(response2.text)

### REMOVE OBJECT WITH PIN/RM ###
response3 = requests.post(endpoint + '/api/v0/pin/rm', params=params, auth=(projectId, projectSecret))
print(response3.json())

I defined the variables ahead of time for privacy. For that specific file, when running the script I got:

<Response [200]>
QmPGKxCwHWYB9TfkYc7HjSPJwjQnsGdQuEf21qLTfRuPdP
<Response [200]>
newimages/1.png
{'Pins': ['QmPGKxCwHWYB9TfkYc7HjSPJwjQnsGdQuEf21qLTfRuPdP']}

What does this mean? Did this work then? How am I able to see this in my browser, Infura, or IPFS?


Solution

  • QmPGKxCwHWYB9TfkYc7HjSPJwjQnsGdQuEf21qLTfRuPdP is called the CID, which is a unique identifier.

    You can access this using the IPFS gateway: https://ipfs.io/ipfs/QmPGKxCwHWYB9TfkYc7HjSPJwjQnsGdQuEf21qLTfRuPdP

    You can see the content as newimages/1.png.

    That means, rather than storing the contents of newimages/1.png, you simply stored the string newimages/1.png in IPFS!


    So you need to change your file object like:

    files = {
        'file': open('newimages/1.png', 'rb')
    }
    

    This will set file to the contents of newimages/1.png.