0

Could someone demonstrate writing a file to IPFS via the HTTP API (/files/write) and Python?

My code is getting messier every time I modify it.

https://pastebin.com/W9eNz1Pb

def api(*argv, **kwargs):
    url = "http://127.0.0.1:5001/api/v0/"
    for arg in argv:
        arg = arg.replace(" ", "/")
        if arg[:-1] != "/":
            arg += "/"
        url += arg
    url = url[0:-1]
    if kwargs:
        url+="?"
        for val in kwargs:
            if val != "post":
                url = url + val + "=" + kwargs[val] + "&"
        url = url[0:-1]
        print(url)
    try:
        if "post" in kwargs:
            print("POST DATA")
            with urllib.request.urlopen(url=url, data=urllib.parse.urlencode(kwargs["post"]).encode("ascii")) as response:
                return response.read()
        else:
            with urllib.request.urlopen(url, timeout=300) as response:
                return response.read()
    except:
        return b"""{"ERROR": "CANNOT CONNECT TO IPFS!"}"""
class file(object):

    def __init__(self, p):
        self.p = p
        if self.p[0] != "/":
            self.p = "/" + self.p

    def read(self):
        return api("files", "read", arg=self.p).decode()

    def write(self, s, *argv):
        if argv:
            return api("files", "write", arg=self.p, offset=str(argv[0]), create="True", parents="True", post={"Data": s})
        else:
            return api("files", "write", arg=self.p, truncate="True", create="True", parents="True", post={"Data": s})

file.read() works perfectly. But file.write() is being a pain in the rear.

2 Answers 2

0

Here's a minimal example to write a file via the /files/write HTTP API in Python:

import requests, urllib

NODE = "http://localhost:5001"
FILE_PATH = "./example" # path to file you're trying to add
MFS_PATH = "/example"   # mfs path you're trying to write to

response = requests.post(NODE+"/api/v0/files/write?arg=%s&create=true" % urllib.parse.quote(MFS_PATH), files={FILE_PATH:open(FILE_PATH, 'rb')})
0
  • make sure ipfs daemon is running

    ipfs init ipfs daemon

  • your url endpoint is wrong. If you check documentaion, for adding file, url should be

    url = "http://127.0.0.1:5001/api/v0/add"
    
  • create a function to upload so u can use this logic in other parts of your project:

    def add_to_ipfs(filepath):
      from pathlib import Path
      import requests
      # rb means open in binary. read binary
      with Path(filepath).open("rb") as fp:
          image_binary=fp.read()
          # we need to make post request to this endpoint.
          url = "http://127.0.0.1:5001/api/v0/add"
          # check the response object
          response = requests.post(url, files={"file": image_binary})
          ipfs_hash=response.json()["Hash"]
           # "./img/myImage.png" -> "myImage.png" split by "/" into array, take the last element 
          filename=filepath.split("/")[-1:][0]
          image_uri=f"https://ipfs.io/ipfs/{ipfs_hash}?filename={filename}"
          print("image uri on ipfs",image_uri)
          return image_uri
    

this is the Response type from ipfs

{
  "Bytes": "<int64>",
  "Hash": "<string>",
  "Name": "<string>",
  "Size": "<string>"
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.