We recently published a new package called Sttp
. Sttp is an enjoyable HTTP client providing a fluent interface to seamlessly compose your HTTP requests. This post provides a brief overview of why Sttp exists and why you should choose it over Axios.
Sttp Series Overview
- an Elegant Axios Wrapper
What is Sttp?
Sttp is an HTTP client for a pleasant developer experience. It wraps the axios library providing a fluent interface to expressively compose your HTTP requests.
Sttp lives as an independent package and is available on NPM. You can install Sttp using npm
(or any other JS package manager) like this:
npm i @supercharge/sttp
Sttp Documentation
An extensive documentation for Sttp is available on superchargejs.com.
Why Use Sttp Over Axios?
Sttp is an axios wrapper. Why not use axios directly? Good question!
Pain Points with Axios
- axios configures requests using objects and editors/IDEs are bad at showing IntelliSense for objects
- the axios configuration is a “guess-game” on what to configure
- do you know from the top of your mind how to add query parameters to axios? (in Sttp it’s as simple as
Sttp.withQueryParams()
) - do you find yourself looking at the axios docs on how to send request payload? Yeah, same here. I hate that.
- axios throws an error when receiving a response with status code
>= 400
(Who thinks throwing an error for a valid response is the correct behavior?)
In Love with Sttp
Sttp solves that config-guessing by providing a fluent and expressive interface. Configure a request using Sttp’s chainable methods. You’ll also notice that Sttp’s requests are more maintainable because they are more readable.
- in Sttp you’re building your requests using a fluent interface
- every chainable Sttp method has a clear and descriptive name, no more guessing
- Sttp always returns a response instance (also for
400
and500
level HTTP responses) - the Sttp response instance comes with handy methods to determine whether it’s a success, redirect, or error response
Sttp Example
You may send a POST request with query parameters, request headers, and payload like this:
import { Sttp } from '@supercharge/sttp'
// or
const { Sttp } = require('@supercharge/sttp')
const response = await Sttp
.withQueryParams({ page: 3 })
.withHeaders({ 'X-API-Token': 123 })
.withPayload({ name: 'Supercharge' })
.post('https://your-api.com/v2/users')
Then use the response
instance to process the returned data. For example, you can call:
if (response.isSuccess()) {
return response.payload()
// { id: 1, name: 'Supercharge' }
}
if (response.isError()) {
return response.payload()
// { statusCode: 401, message: 'Invalid X-API-Token' }
}
A Reminder to Check the Sttp Docs
Please have a look at the Sttp docs for more examples and descriptions 😃
Enjoy Sttp!
Mentioned Resources
- @supercharge/sttp repo on GitHub
- axios repo on GitHub
- Sttp docs on superchargejs.com