Subscribe to PHP Freaks RSS

Ketting v6: Using Hypermedia APIs with React

syndicated from planet-php.net on September 9, 2020

We just released Ketting 6. This is the accumulation of about a year of learning on how to better integrate REST APIs with frontend frameworks, in particular React.



It’s packed with new features such as local state management, new caching strategies, (client-side) middleware support and change events. It’s also the first release that has some larger BC breaks to make this all work.



Releasing Ketting 6 is a big personal milestone for me, and I’m really excited to unleash it to the world and see what people do with. A big thank you to all the people that beta tested this in the last several months!



What’s Ketting?



In short: Ketting is a generic REST client for Javascript. You can use it for pushing JSON objects via HTTP, but the richer your API is in terms of best practices and standard formats, the more it can automatically do for you.



It has support for Hypermedia formats such as HAL, Siren, Collection+JSON, JSON:API and can even understand and follow links from html.



It’s often said that REST (and Hypermedia APIs) is lacking a good generic client. GraphQL has a lot of advantages, but a major one is tooling. Ketting aims to close that gap.



More information can be found on Github.



React support in Ketting 6



Ketting now has a separate react-ketting package that provides React bindings to Ketting. These bindings should look very familiar if you’ve used Apollo Client in the past.



Lets dive into an example:



Lets assume you have a REST api that has an ‘article’ endpoint. This returns something like:



{
  "title": "Hello world",
  "body": "..."
}


This article is retrieved with GET, and updated with PUT, this is how you would display it:



import { useResource } from 'react-ketting';

export function Article() {

const { loading, error, data } = useResource('https://api.example/article/5');

if (loading) { return <div>Loading...</div>; }

if (error) { return <div class="error">{error.message}</div>; }

return <article> <h1>{data.title}<

Truncated by Planet PHP, read more at the original (another 9131 bytes)