Query Clients are an SDK for the Web

Published Sat Jan 20 2024

SDKs and APIs are common tools in software development. When developing for the web, a REST API is the most common target for integration. While there is benefit to many APIs behaving in the same way, some niceties gained when using an SDK are lost.

An SDK is a layer of abstraction to make using an API more convenient. The most important difference between an SDK and an API is the ability to hide complexity. For the web this can come in many forms:

  • Constructing requests: headers, body, URL
  • Parsing responses
  • Parsing errors
  • Authentication
  • Caching

These are all important and common problems that must be solved in a web application today. Using a query client can help you avoid re-writing the same mass of boilerplate code in every application you write. Here are some example query clients:

The biggest benefit I’ve seen is mass removal of repetitive request/response handling code. I can’t even count how many times I’ve seen the following lines:

try {
	const response = await fetch(url, options);
	const json = await response.json();
} catch (error) {
	// proceed to do nothing with the error

If this was all you needed then I wouldn’t be so insistent on using a query client. However the first implementation is never enough. You will soon realize that this code cannot live with your UI, it must be outside. Once moved outside you will create state to watch the loading state, error status, and successful responses. As your code continues it’s life cycle from a young and simple state, it will mature into a complex mess along with the other 20 requests your application makes.

By using a query client, whether open sourced or perhaps your own, you encapsulate the complexity of the request response cycle. This will enable you to develop a web UI in bliss, unaware of the difficulties of asynchronous code except when absolutely necessary.