PinataCloud / Pinata-SDK

Official SDK for the Pinata IPFS service
MIT License
271 stars 67 forks source link
hacktoberfest

Pinata SDK (Archived)

This is the older Node.js SDK that is no longer being maintained.

A new Pinata SDK is available for download

npm i pinata

Visit the docs for more information

Overview

The Pinata NodeJS SDK provides the quickest / easiest path for interacting with the Pinata API.

Installation

npm install --save @pinata/sdk

Setup

To start, simply require the Pinata SDK and set up an instance with your Pinata API Keys or your JWT key. Don't know what your keys are? Check out your Account Page. In the example below we provided with 3 ways to call the pinata SDK.

// Use the api keys by providing the strings directly 
const pinataSDK = require('@pinata/sdk');
const pinata = new pinataSDK('yourPinataApiKey', 'yourPinataSecretApiKey');
// Use the api keys by specifying your api key and api secret
const pinataSDK = require('@pinata/sdk');
const pinata = new pinataSDK({ pinataApiKey: 'yourPinataApiKey', pinataSecretApiKey: 'yourPinataSecretApiKey' });
// Use the JWT key
const pinataSDK = require('@pinata/sdk');
const pinata = new pinataSDK({ pinataJWTKey: 'yourPinataJWTKey'});

Quickly test that you can connect to the API with the following call:

pinata.testAuthentication().then((result) => {
    //handle successful authentication here
    console.log(result);
}).catch((err) => {
    //handle error here
    console.log(err);
});

Usage

Once you've set up your instance, using the Pinata SDK is easy. Simply call your desired function and handle the results of the promise.

hashMetadata

Allows the user to change the name and keyvalues associated with content pinned to Pinata. Changes made via this endpoint only affect the metadata for the hash passed in. Metadata is specific to Pinata and does not modify the actual content stored on IPFS in any way. It is simply a convenient way of keeping track of what content you have stored.

pinata.hashMetadata(ipfsPinHash, metadata)
Params
Adding or modifying keyvalues

To add or modify existing keyvalues, simply provide them in the following format for the keyvalues object:

keyvalues: {
    newKey: 'newValue', //this adds a keyvalue pair
    existingKey: 'newValue' //this modifies the value of an existing key if that key already exists
}
Removing keyvalues

To remove a keyvalue pair, simply provide null as the value for an existing key like so:

keyvalues: {
    existingKeyToRemove: null //this removes a keyvalue pair
}

Response

If the operation is successful, you will receive back an "OK" REST 200 status.

Example Code
const metadata = {
    name: 'new custom name',
    keyvalues: {
        newKey: 'newValue',
        existingKey: 'newValue',
        existingKeyToRemove: null
    }
};
pinata.hashMetadata('yourHashHere', metadata).then((result) => {
    //handle results here
    console.log(result);
}).catch((err) => {
    //handle error here
    console.log(err);
});

pinByHash

Adds a hash to Pinata's pin queue to be pinned asynchronously. For the synchronous version of this operation see: pinHashToIPFS

pinata.pinByHash(hashToPin, options)
Params

pinFileToIPFS

Send a file to Pinata for direct pinning to IPFS.

pinata.pinFileToIPFS(readableStream, options)
Params

pinFromFS

Read from a location on your local file system and recursively pin the contents to IPFS (node.js only).

Both individual files, as well as directories can be read from.

pinata.pinFromFS(sourcePath, options)
Params

pinJobs

This endpoint allows users to search for the status of all hashes that are currently in Pinata's pin queue. Records in the pin queue arrived there through either the pinByHash operation or by failing during a pinHashToIPFS operation.

pinata.pinJobs(filters)
Params

pinJSONToIPFS

Send JSON to Pinata for direct pinning to IPFS.

pinata.pinJSONToIPFS(body, options)
Params

unpin

Have Pinata unpin content that you've pinned through the service.

pinata.unpin(hashToUnpin)
Params

testAuthentication

Tests that you can authenticate with Pinata correctly

pinata.testAuthentication()
Params

None

Response

{
    authenticated: true
}
Example Code
pinata.testAuthentication().then((result) => {
    //handle results here
    console.log(result);
}).catch((err) => {
    //handle error here
    console.log(err);
});

pinList

Retrieve pin records for your Pinata account. In order to get the next page you have to manipulate pageLimit and pageOffset filter to get the next page. This method no longer return the total count of pins. We highly encourage you to use the auto-pagination method getFilesByCount.

pinata.pinList(filters)
Params
Metadata filter object formatting
{
    name: 'exampleName',
    keyvalues: {
        testKeyValue: {
            value: 'exampleFilterValue',
            op: 'exampleFilterOperation'
        },
        testKeyValue2: {
            value: 'exampleFilterValue2',
            op: 'exampleFilterOperation2'
        }
    }
}

Filter explanations:

As an example, the following filter would only find records whose name contains the letters 'invoice', have the metadata key 'company' with a value of 'exampleCompany', and have a metadata key 'total' with values between 500 and 1000:

{
    name: 'invoice',
    keyvalues: {
        company: {
            value: 'exampleCompany,
            op: 'eq'
        },
        total: {
            value: 500,
            secondValue: 1000,
            op: 'between'
        }
    }
}

Our libraries support auto-pagination. This feature easily handles fetching large lists of resources without having to manually paginate results and perform subsequent requests.

To use the auto-pagination feature in Node 10+, simply iterate over a "list" call with the parameters you need in a for await loop.

getFilesByCount

This method support auto-pagination. This feature easily handles fetching large lists of pin records for your Pinata account without having to manually paginate results and perform subsequent requests. To use the auto-pagination feature in Node 10+.

pinata.getFilesByCount(filters, count)
Params
Metadata filter object formatting
{
    name: 'exampleName',
    keyvalues: {
        testKeyValue: {
            value: 'exampleFilterValue',
            op: 'exampleFilterOperation'
        },
        testKeyValue2: {
            value: 'exampleFilterValue2',
            op: 'exampleFilterOperation2'
        }
    }
}

Filter explanations:


#### Response

[ { id: (the id of your pin instance record), ipfs_pin_hash: (the IPFS multi-hash for the content you pinned), size: (this is how large (in bytes) the content pinned is), user_id: (this is your user id for Pinata), date_pinned: (This is the timestamp for when this content was pinned - represented in ISO 8601 format), date_unpinned: (This is the timestamp for when this content was unpinned (if null, then you still have the content pinned on Pinata), metadata: { name: (this will be the name of the file originally uploaded, or the custom name you set), keyvalues: { exampleCustomKey: "exampleCustomValue", exampleCustomKey2: "exampleCustomValue2", ... } } }, { same record format as above } . . . ]

##### Example Code

```javascript
const pinataSDK = require('@pinata/sdk');
const pinata = pinataSDK('yourPinataApiKey', 'yourPinataSecretApiKey');

const metadataFilter = {
    name: 'exampleName',
    keyvalues: {
        testKeyValue: {
            value: 'exampleFilterValue',
            op: 'exampleFilterOperation'
        },
        testKeyValue2: {
            value: 'exampleFilterValue2',
            op: 'exampleFilterOperation2'
        }
    }
};

const filters = {
    status : 'pinned',
    pageLimit: 10,
    pageOffset: 0,
    metadata: metadataFilter
};

 // more reference at [for await ...](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of)
 for await (const item of pinata.getFilesByCount(filters, 35)) {
    // ...(item) perform any task with the current item in the array of 35
 }

for await (const item of pinata.getFilesByCount(filters)) {
    // ...(item) perform any task with the current item the array is determined by all your pins
 }

userPinnedDataTotal

Returns the total combined size (in bytes) of all content you currently have pinned on Pinata.

pinata.userPinnedDataTotal()
Params

None

Response

The response for this call will the total combined size of everything you currently have pinned on pinata. This value will be expressed in bytes

Example Code
pinata.userPinnedDataTotal().then((result) => {
    //handle results here
    console.log(result);
}).catch((err) => {
    //handle error here
    console.log(err);
});

Host Node Multiaddresses

For endpoints that involve Pinata finding and pinning content that already resides on the IPFS network, you can help Pinata find your content faster by optionally providing us with the "multiaddresses" up to five host nodes that your content already resides on.

To find the multiaddresses of your nodes, simply run the following on your node's command line:

ipfs id

In the response, you'll want to focus on the "Addresses" array that's returned. Here you'll find the multiaddresses of your node. These multiaddresses are what other IPFS nodes use to connect to your node.

In the "Addresses" array, take note of the multiaddress that contains your external IP address. Not the local ipv4 "127.0.0.1" address or the local ipv6 "::1" address.

Here's an example of what a full external ipv4 multiaddress would look like (your IP address and node ID will differ):

/ip4/123.456.78.90/tcp/4001/ipfs/QmAbCdEfGhIjKlMnOpQrStUvWxYzAbCdEfGhIjKlMnOpQr

⚠️ Please make sure every node provided is online. Pinata will attempt to connect to all nodes before pinning the content, and if any these nodes are offline, your request will eventually fail.

Pin Policies

A pin policy tells Pinata how many times content should be replicated, and where that content should be replicated at.

To read more about pin policies, please check out the Regions and Replications Documentation.

Pin policies take the following form:

Example pin policy object
{
    regions: [
        {
            id: 'FRA1',
            desiredReplicationCount: 1
        },
        {
            id: 'NYC1',
            desiredReplicationCount: 2
        }
    ]
}

The ids of currently available public regions are:

• FRA1 - Frankfurt, Germany (max 2 replications)

• NYC1 - New York City, USA (max 2 replications)

Pinata Metadata

For endpoints that allow you to add content, Pinata lets you add optionally metadata for that content. This metadata can later be used for querying on what you've pinned with our userPinList endpoint. Providing metadata does not alter your content or how it is stored on IPFS in any way.

The metadata object can consist of the following values:

Example metadata object
{
    name: "customName",
    keyvalues: {
        customKey: "customValue",
        customKey2: "customValue2"
    }
}

Pinata Options

Some endpoints allow you to pass additional options for Pinata to take into account when adding content to IPFS.

The options object can consist of the following values:

Example pinataOptions object
{
    cidVersion: 1,
    wrapWithDirectory: true
}

Questions? Issues? Suggestions?

Feel free to file a github issue or email us at team@pinata.cloud

We'd love to hear from you!