Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

ipfs-api

ipfs24.1kMITdeprecated26.1.2

ipfs-api has been renamed to ipfs-http-client, please update your package.json to get the latest version.

A client library for the IPFS HTTP API

ipfs

readme

IPFS http client lib logo

The JavaScript HTTP client library for IPFS implementations.



A client library for the IPFS HTTP API, implemented in JavaScript. This client library implements the interface-ipfs-core enabling applications to change between an embedded js-ipfs node and any remote IPFS node without having to change the code. In addition, this client library implements a set of utility functions.

Lead Maintainer

Alan Shaw.

Table of Contents

Install

This module uses node.js, and can be installed through npm:

npm install --save ipfs-api

We support both the Current and Active LTS versions of Node.js. Please see nodejs.org for what these currently are.

Running the daemon with the right port

To interact with the API, you need to have a local daemon running. It needs to be open on the right port. 5001 is the default, and is used in the examples below, but it can be set to whatever you need.

# Show the ipfs config API port to check it is correct
> ipfs config Addresses.API
/ip4/127.0.0.1/tcp/5001
# Set it if it does not match the above output
> ipfs config Addresses.API /ip4/127.0.0.1/tcp/5001
# Restart the daemon after changing the config

# Run the daemon
> ipfs daemon

Importing the module and usage

var ipfsAPI = require('ipfs-api')

// connect to ipfs daemon API server
var ipfs = ipfsAPI('localhost', '5001', {protocol: 'http'}) // leaving out the arguments will default to these values

// or connect with multiaddr
var ipfs = ipfsAPI('/ip4/127.0.0.1/tcp/5001')

// or using options
var ipfs = ipfsAPI({host: 'localhost', port: '5001', protocol: 'http'})

// or specifying a specific API path
var ipfs = ipfsAPI({host: '1.1.1.1', port: '80', 'api-path': '/ipfs/api/v0'})

Importing a sub-module and usage

const bitswap = require('ipfs-api/src/bitswap')('/ip4/127.0.0.1/tcp/5001')

bitswap.unwant(key, (err) => {
  // ...
})

In a web browser through Browserify

Same as in Node.js, you just have to browserify the code before serving it. See the browserify repo for how to do that.

See the example in the examples folder to get a boilerplate.

In a web browser through webpack

See the example in the examples folder to get an idea on how to use js-ipfs-api with webpack.

In a web browser from CDN

Instead of a local installation (and browserification) you may request a remote copy of IPFS API from unpkg CDN.

To always request the latest version, use the following:

<!-- loading the minified version -->
<script src="https://unpkg.com/ipfs-api/dist/index.min.js"></script>

<!-- loading the human-readable (not minified) version -->
<script src="https://unpkg.com/ipfs-api/dist/index.js"></script>

For maximum security you may also decide to:

  • reference a specific version of IPFS API (to prevent unexpected breaking changes when a newer latest version is published)
  • generate a SRI hash of that version and use it to ensure integrity
  • set the CORS settings attribute to make anonymous requests to CDN

Example:

<script src="https://unpkg.com/ipfs-api@9.0.0/dist/index.js"
integrity="sha384-5bXRcW9kyxxnSMbOoHzraqa7Z0PQWIao+cgeg327zit1hz5LZCEbIMx/LWKPReuB"
crossorigin="anonymous"></script>

CDN-based IPFS API provides the IpfsApi constructor as a method of the global window object. Example:

var ipfs = window.IpfsApi('localhost', '5001')

If you omit the host and port, the API will parse window.host, and use this information. This also works, and can be useful if you want to write apps that can be run from multiple different gateways:

var ipfs = window.IpfsApi()

CORS

In a web browser IPFS API (either browserified or CDN-based) might encounter an error saying that the origin is not allowed. This would be a CORS ("Cross Origin Resource Sharing") failure: IPFS servers are designed to reject requests from unknown domains by default. You can whitelist the domain that you are calling from by changing your ipfs config like this:

ipfs config --json API.HTTPHeaders.Access-Control-Allow-Origin "[\"http://example.com\"]"
ipfs config --json API.HTTPHeaders.Access-Control-Allow-Credentials "[\"true\"]"
ipfs config --json API.HTTPHeaders.Access-Control-Allow-Methods "[\"PUT\", \"POST\", \"GET\"]"

Custom Headers

If you wish to send custom headers with each request made by this library, for example, the Authorization header. You can use the config to do so:

const ipfs = IpfsApi({
  host: 'localhost',
  port: 5001,
  protocol: 'http',
  headers: {
    authorization: 'Bearer ' + TOKEN
  }
})

Usage

API

IPFS Core API Compatible

js-ipfs-api follows the spec defined by interface-ipfs-core, which concerns the interface to expect from IPFS implementations. This interface is a currently active endeavor. You can use it today to consult the methods available.

Files

Graph

Network

Node Management

Pubsub Caveat

Currently, the PubSub API only works in Node.js environment

We currently don't support pubsub when run in the browser, and we test it with separate set of tests to make sure if it's being used in the browser, pubsub errors.

More info: https://github.com/ipfs/js-ipfs-api/issues/518

This means:

  • You can use pubsub from js-ipfs-api in Node.js
  • You can use pubsub from js-ipfs-api in Electron (when js-ipfs-api is ran in the main process of Electron)
  • You can't use pubsub from js-ipfs-api in the browser
  • You can't use pubsub from js-ipfs-api in Electron's renderer process
  • You can use pubsub from js-ipfs in the browsers
  • You can use pubsub from js-ipfs in Node.js
  • You can use pubsub from js-ipfs in Electron (in both the main process and the renderer process)
  • See https://github.com/ipfs/js-ipfs for details on pubsub in js-ipfs

Domain data types

A set of data types are exposed directly from the IPFS instance under ipfs.types. That way you're not required to import/require the following.

Utility functions

Adding to the methods defined by interface-ipfs-core, js-ipfs-api exposes a set of extra utility methods. These utility functions are scoped behind the ipfs.util.

Complete documentation for these methods is coming with: https://github.com/ipfs/js-ipfs-api/pull/305

Add files or entire directories from the FileSystem to IPFS

ipfs.util.addFromFs(path, option, callback)

Reads a file or folder from path on the filesystem and adds it to IPFS. Options:

  • recursive: If path is a directory, use option { recursive: true } to add the directory and all its sub-directories.
    • ignore: To exclude fileglobs from the directory, use option { ignore: ['ignore/this/folder/**', 'and/this/file'] }.
    • hidden: hidden/dot files (files or folders starting with a ., for example, .git/) are not included by default. To add them, use the option { hidden: true }.
ipfs.util.addFromFs('path/to/a/folder', { recursive: true , ignore: ['subfolder/to/ignore/**']}, (err, result) => {
  if (err) { throw err }
  console.log(result)
})

result is an array of objects describing the files that were added, such as:

[
  {
    path: 'test-folder',
    hash: 'QmRNjDeKStKGTQXnJ2NFqeQ9oW23WcpbmvCVrpDHgDg3T6',
    size: 2278
  },
  // ...
]
Add a file from a URL to IPFS

ipfs.util.addFromURL(url, callback)

ipfs.util.addFromURL('http://example.com/', (err, result) => {
  if (err) {
    throw err
  }
  console.log(result)
})
Add a file from a stream to IPFS

ipfs.util.addFromStream(stream, callback)

This is very similar to ipfs.files.add({path:'', content: stream}). It is like the reverse of cat

ipfs.util.addFromStream(<readable-stream>, (err, result) => {
  if (err) {
    throw err
  }
  console.log(result)
})
Get endpoint configuration (host and port)

ipfs.util.getEndpointConfig()

This returns an object containing the host and the port

Get libp2p crypto primitives

ipfs.util.crypto

This contains an object with the crypto primitives

Get is-ipfs utilities

ipfs.util.isIPFS

This contains an object with the is-ipfs utilities to help identifying IPFS resources

Callbacks and Promises

If you do not pass in a callback all API functions will return a Promise. For example:

ipfs.id()
  .then((id) => {
    console.log('my id is: ', id)
  })
  .catch((err) => {
    console.log('Fail: ', err)
  })

This relies on a global Promise object. If you are in an environment where that is not yet available you need to bring your own polyfill.

Development

Testing

We run tests by executing npm test in a terminal window. This will run both Node.js and Browser tests, both in Chrome and PhantomJS. To ensure that the module conforms with the interface-ipfs-core spec, we run the batch of tests provided by the interface module, which can be found here.

Contribute

The js-ipfs-api is a work in progress. As such, there's a few things you can do right now to help out:

  • Check out the existing issues!
  • Perform code reviews. More eyes will help a) speed the project along b) ensure quality and c) reduce possible future bugs.
  • Add tests. There can never be enough tests. Note that interface tests exist inside interface-ipfs-core.
  • Contribute to the FAQ repository with any questions you have about IPFS or any of the relevant technology. A good example would be asking, 'What is a merkledag tree?'. If you don't know a term, odds are, someone else doesn't either. Eventually, we should have a good understanding of where we need to improve communications and teaching together to make IPFS and IPN better.

Want to hack on IPFS?

Historical context

This module started as a direct mapping from the go-ipfs cli to a JavaScript implementation, although this was useful and familiar to a lot of developers that were coming to IPFS for the first time, it also created some confusion on how to operate the core of IPFS and have access to the full capacity of the protocol. After much consideration, we decided to create interface-ipfs-core with the goal of standardizing the interface of a core implementation of IPFS, and keep the utility functions the IPFS community learned to use and love, such as reading files from disk and storing them directly to IPFS.

License

MIT

FOSSA Status

changelog

26.1.2 (2018-11-03)

Features

  • go-ipfs 0.4.18 (e3e4d6c)
  • upload example works with big files (62b844f)

26.1.1 (2018-11-03)

Features

26.1.0 (2018-10-31)

Bug Fixes

  • make ping not mix errors with responses (#883) (80725f2)

26.0.3 (2018-10-31)

26.0.2 (2018-10-31)

Bug Fixes

26.0.1 (2018-10-30)

26.0.0 (2018-10-30)

Bug Fixes

  • add missing and remove unused dependencies (#879) (979d8b5)

Chores

Features

BREAKING CHANGES

  • dag-cbor nodes now represent links as CID objects

The API for dag-cbor changed. Links are no longer represented as JSON objects ({"/": "base-encoded-cid"}, but as CID objects. ipfs.dag.get() and now always return links as CID objects. ipfs.dag.put() also expects links to be represented as CID objects. The old-style JSON objects representation is still supported, but deprecated.

Prior to this change:

const cid = new CID('QmXed8RihWcWFXRRmfSRG9yFjEbXNxu1bDwgCFAN8Dxcq5')
// Link as JSON object representation
const putCid = await ipfs.dag.put({link: {'/': cid.toBaseEncodedString()}})
const result = await ipfs.dag.get(putCid)
console.log(result.value)

Output:

{ link:
   { '/':
      <Buffer 12 20 8a…> } }

Now:

const cid = new CID('QmXed8RihWcWFXRRmfSRG9yFjEbXNxu1bDwgCFAN8Dxcq5')
// Link as CID object
const putCid = await ipfs.dag.put({link: cid})
const result = await ipfs.dag.get(putCid)
console.log(result.value)

Output:

{ link:
   CID {
     codec: 'dag-pb',
     version: 0,
     multihash:
      <Buffer 12 20 8a…> } }

See https://github.com/ipld/ipld/issues/44 for more information on why this change was made.

  • remove types.dagCBOR and types.dagPB from public API

If you need the ipld-dag-cbor or ipld-dag-pb module in the Browser, you need to bundle them yourself.

25.0.0 (2018-10-15)

Bug Fixes

24.0.2 (2018-09-21)

Bug Fixes

24.0.1 (2018-08-21)

24.0.0 (2018-08-15)

Bug Fixes

  • add test data to IPFS before fetching it (#832) (b2a77d6)
  • BREAKING CHANGE use data-encoding arg so data is not corrupted (#806) (553c3fb)
  • dag.get return error on missing multicodec (#831) (ff7c7e5)
  • remove external urls from addFromURL tests (#834) (7cf7998), closes #803

BREAKING CHANGES

  • Requires go-ipfs 0.4.17 as it allows for specifying the data encoding format when requesting object data.

23.0.0 (2018-08-06)

Bug Fixes

Features

22.3.0 (2018-08-02)

Bug Fixes

Features

  • compatible with go-ipfs 0.4.16 (8536ee4)
  • expose mfs files.read*Stream methods (#823) (70c9df1)

22.2.4 (2018-07-17)

Bug Fixes

  • increase browserNoActivityTimeout to account for before (328e338)
  • increase timeout for .name after all (3dc4313)
  • missing debug dependency fixes #809 (#810) (0f1fe95)

22.2.3 (2018-07-10)

Bug Fixes

22.2.2 (2018-07-05)

Bug Fixes

  • ignore response body for some mfs commands (#805) (b604a64)

Features

22.2.1 (2018-06-29)

Bug Fixes

  • res.req only in Node.js, in browser use res.url instead (#798) (e8a5ab9)

22.2.0 (2018-06-29)

Features

  • logs path & querystring for requests (#796) (4e55d19)

22.1.1 (2018-06-25)

Bug Fixes

22.1.0 (2018-06-18)

Features

  • add support for custom headers to send-request (#741) (7fb2e07)
  • implement bitswap wantlist peer ID param and bitswap unwant (#761) (73a153e)

22.0.2 (2018-06-14)

Bug Fixes

  • json-loader error in upload-file-via-browser example (#784) (5e7b7c4)

22.0.1 (2018-05-30)

Bug Fixes

  • configure webpack to not use esmodules in dependencies (dc14333)
  • correctly differentiate pong responses (4ad25a3)
  • util.addFromURL with URL-escaped file (a3bd811)

22.0.0 (2018-05-20)

Bug Fixes

  • callback from unsub after stream ends (51a80f2)
  • do not fail stop node if failed start node (533760f)
  • ping: convert the ping messages to lowercase (632af40)
  • more robust ping tests (fc6d301)
  • remove .only (0e21c8a)
  • result.Peers can be null, ensure callback is called (f5f2e83)
  • update asserted error message (17c1f1c)
  • use async/setImmediate vs process.nextTick (faa51b4)

21.0.0 (2018-05-12)

Bug Fixes

  • make pubsub.unsubscribe async and alter pubsub.subscribe signature (b98f8f3)

BREAKING CHANGES

  • pubsub.unsubscribe is now async and argument order for pubsub.subscribe has changed

License: MIT Signed-off-by: Alan Shaw alan@tableflip.io

20.2.1 (2018-05-06)

20.2.0 (2018-04-30)

Bug Fixes

  • adding files by pull stream (2fa16c5)
  • handle request errors in addFromURL (7c5cea5)
  • increase timeout for name.publish and fix setup code (ceb1106)
  • ipfs add url wrap doesn't work (#750) (f6f1bf0)

Features

  • Add offset/length arguments to files.cat (17967c1)
  • get it ready for release (#751) (1885af4)

20.1.0 (2018-04-30)

Bug Fixes

  • adding files by pull stream (2fa16c5)
  • handle request errors in addFromURL (7c5cea5)
  • increase timeout for name.publish and fix setup code (ceb1106)
  • ipfs add url wrap doesn't work (#750) (f6f1bf0)

Features

  • Add offset/length arguments to files.cat (17967c1)
  • get it ready for release (#751) (1885af4)

20.0.1 (2018-04-12)

20.0.0 (2018-04-05)

Bug Fixes

  • dag: js-ipld format resolver take the raw block (2683c7e)
  • dag: path logic for DAG get was wrong (d2b203b)
  • dag: use SendOneFile for dag put (9c37213)

Features

  • dag.put (9463d3a)
  • dag: proper get implementation (7ba0343)
  • dag: rebase, use waterfall for put (ad9eab8)
  • dag: update option names to reflect go-ipfs API (9bf1c6c)
  • Provide access to bundled libraries when in browser (#732) (994bdad), closes #406
  • public-readonly-method-for-getting-host-and-port (41d32e3), closes #580
  • Wrap with dir (#730) (160860e)

19.0.0 (2018-03-28)

Bug Fixes

  • bitswap: 0.4.14 returns empty array instead of null (5e37a54)
  • ping: tests were failing and there it was missing to catch when count and n are used at the same time (2181568)

Features

  • streamable ping and optional packet number (#723) (3f3ce8a)

18.2.1 (2018-03-22)

Features

  • add ability to files.cat with a cid instance (aeeb94e)

18.2.0 (2018-03-16)

Bug Fixes

  • disable Browser test on Windows (385a6c3)
  • don't create one webpack bundle for every test file (3967e96)
  • last fixes for green (#719) (658bad2)
  • set the FileResultStreamConverter explicitly (dfad55e), closes #696
  • use a different remote server for test (1fc15a5)

Features

18.1.2 (2018-03-09)

Bug Fixes

18.1.1 (2018-02-20)

Features

  • support recursive ipfs ls (cfe95f6)

18.1.0 (2018-02-20)

Features

  • support recursive ipfs ls (cfe95f6)

18.0.0 (2018-02-14)

Bug Fixes

  • exception when dir is empty (#680) (ec04f6e)
  • support all the Buffer shims and load fixtures correctly (066988f)
  • update stats API (#684) (4f7999d)

Features

  • (breaking change) stats spec, spec repo, stream to value on files read (#679) (118456e)
  • breaking change: use stream on stats.bw (#686) (895760e)
  • ipfs.stop (5091115)

17.5.0 (2018-01-24)

Bug Fixes

Features

17.4.0 (2018-01-24)

Bug Fixes

Features

  • integrate new ipfsd-ctl (2b1820b)

17.3.0 (2018-01-12)

Features

17.2.7 (2018-01-11)

Bug Fixes

Features

17.2.6 (2017-12-28)

Features

17.2.5 (2017-12-20)

Bug Fixes

  • files.add: handle weird directory names (#646) (012b86c)

Features

17.2.4 (2017-12-06)

Bug Fixes

17.2.3 (2017-12-05)

17.2.2 (2017-12-05)

17.2.1 (2017-12-05)

Features

17.2.0 (2017-12-01)

Bug Fixes

17.1.3 (2017-11-23)

17.1.2 (2017-11-22)

Bug Fixes

17.1.1 (2017-11-22)

Bug Fixes

17.1.0 (2017-11-20)

Features

  • send files HTTP request should stream (#629) (dae62cb)

17.0.1 (2017-11-20)

Bug Fixes

17.0.0 (2017-11-17)

Features

16.0.0 (2017-11-16)

Bug Fixes

15.1.0 (2017-11-14)

Bug Fixes

  • adapting HTTP API to the interface-ipfs-core spec (#625) (8e58225)

Features

15.0.2 (2017-11-13)

15.0.1 (2017-10-22)

15.0.0 (2017-10-22)

Features

  • update pin API to match interface-ipfs-core (9102643)

14.3.7 (2017-10-18)

14.3.6 (2017-10-18)

Bug Fixes

  • pass the config protocol to http requests (#609) (38d7289)

Features

  • avoid doing multiple RPC requests for files.add, fixes #522 (#595) (0ea5f57)
  • report progress on ipfs add (e2d894c)

14.3.5 (2017-09-08)

Features

  • Support specify hash algorithm in files.add (#597) (ed68657)

14.3.4 (2017-09-07)

14.3.3 (2017-09-07)

Features

  • support options for .add / files.add (8c717b2)

14.3.2 (2017-09-04)

Bug Fixes