@wp-headless/react v0.9.11
Fetch (alpha)
A Wordpress API client that works both in the browser and in Node. Tiny footprint, > 95% code coverage, browser tested down to IE11, tree shakable CJS and ES6 builds, expressive syntax.
Why?
There are great alternatives such as wpapi and yllet although both of these projects have issues:
- Long unresolved browser issues
- Bloated packages size
- No tree-shakable ESM or CJS build available
- Opinionated API that attempts to do more then is needed.
- Lack of automated browser testing and coverage
We intend to build support lean and well tested packages that fit into the modern ES6 javascript ecosystem.
Installation
The architecture of Fetch allows you to specify your own transport layer such as fetch or axios. (read more)
Yarn
yarn add @wp-headless/client @wp-headless/transport-fetch
NPM
npm install @wp-headless/client @wp-headless/transport-fetch
Usage
Creating a client instance bound to the endpoint of your Wordpress install:
import Client from '@wp-headless/client';
import FetchTransport from '@wp-headless/transport-fetch';
const client = new Client({
endpoint: 'https://demo.wp-api.org/wp-json',
transport: new FetchTransport()
});
You may also use another transport layer such as axios:
import Client from '@wp-headless/client';
import AxiosTransport from '@wp-headless/transport-axios';
const client = new Client({
endpoint: 'https://demo.wp-api.org/wp-json',
transport: new AxiosTransport()
});
Fetching posts using async await:
const posts = await client.posts().get();
Or with promises:
client.posts().get().then(posts => {
console.log(posts);
});
Resources
Client instances provide the following API resource methods:
client.categories()
client.comments()
client.media()
client.statuses()
client.posts()
client.pages()
client.settings()
client.tags()
client.taxonomies()
client.types()
client.users()
These resource methods are simply syntax sugar for setting the path and namespace to an API resource. Therefore the following are equivalent:
const post = await client.posts().get(1);
const post = await client.get('posts/1');
Adding custom request methods is easy (example WooCommerce REST API), the following would fetch the enpoint http://demo.wp-api.org/wp-json/wc/v2/products:
client.products = () => client.namespace('wc/v2').resource('products');
const products = await client.products().get();
Of course you could simply also do the following:
const dogBone = await client.namespace('wc/v2').get('products/123');
Methods
Client instances also provide access to HTTP methods to access API resources.
client.get(); // Http GET
client.create(); // Http POST
client.update(); // Http PATCH
client.delete(); // Http DELETE
Params
You can pass request parameters as an object to any of the above methods:
const post = client.posts().create({
title: 'Hello World!',
content: 'Lorem ipsum dolor sit amet...',
excerpt: 'Etiam at feugiat neque...'
});
You may write parameters as camel case or snake case:
const post = client.posts().create({ perPage: 10 });
const posts = client.posts().get({ per_page: 10 });
Its also possible to set global params that will be sent with each request:
// Sets single param key/value
client.param('source', 'wp-headless');
// Merges object with current global param values
client.param({
source: 'wp-headless',
perPage: 15,
orderby: 'title'
});
To retrieve global params:
// Single value
client.param('source'); // wp-headless
// All values
client.params;
Embed data
WordPress API supports embedding of resources and instead of having to provide _embed=true as a param on every request you can simpley use embed() before any request methods.
More about WordPress API embedding can you read here.
const posts = await client.posts().embed().get({
slug: 'hello-world'
});
File uploading
When Uploading a file you can use client.file(file, [name])
to specify a file or a file buffer to attach to the request with a name (optional).
In the browser:
const file = document.getElementById('upload-input').files[0];
const upload = await client.media().file(file, 'Puppy Dog').create({
title: 'Puppy dog with a bone'
});
In Node:
const file = fs.createReadStream('test.jpg');
client.media().file(file, 'Puppy Dog').create({
title: 'Puppy dog with a bone'
});
Transport Layers
The architecture of Fetch allows you to specify your own transport layer such as fetch or axios. This allows devs to use a library that they are familiar with, and perhaps are already using in their app, saving bundle size.
Fetch
The fetch transport layer uses the Fetch API Standard to make requests. This is supported in all modern browsers and newer versions of Node. This is what our team uses.
To support older browsers you will have to implement a polyfill such as isomorphic-fetch or (isomorphic-unfetch)https://github.com/developit/unfetch/tree/master/packages/isomorphic-unfetch:
yarn add @wp-headless/client @wp-headless/transport-fetch isomorphic-unfetch
import 'isomorphic-unfetch';
import Client from '@wp-headless/client';
import FetchTransport from '@wp-headless/transport-fetch';
const client = new Client({
endpoint: 'https://demo.wp-api.org/wp-json',
transport: new FetchTransport()
});
Axios
Axios is a popular HTTP request package that is usable in Node and the browser, no polyfill is needed. Although it does have a larger bundle size:
import Client from '@wp-headless/client';
import AxiosTransport from '@wp-headless/transport-axios';
const client = new Client({
endpoint: 'https://demo.wp-api.org/wp-json',
transport: new AxiosTransport()
});
Others
We endevour to release other transport layers for superagent and ky in the future. We would love community contributions!
Examples
Examples of usage in a real world application can be found in the examples
folder.
Thanks
Thanks to BrowserStack for lending us their amazing infrastructure to give us automated browser coverage
Thanks to Drone an incredible pure docker CI/CD platform built on golang for building our stack!
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago