unrested
Minimal, type-safe REST client using JS proxies.
โน๏ธ If you like this package, upvote this feature to be part of
unjs/ofetch
Much appreciated.
Features
- ๐ Lightweight, only 36 loc
- ๐ฆพ Strongly typed
- ๐ Supports chain and bracket syntax
api.nested.users(1).get()
- or
api.nested.users["1"].get()
- ๐ชต Use other HTTP methods, like
.post()
unrested
uses ofetch for data fetching under the hood. Thus, every option available for ofetch is usable with unrested as well!
Installation
Run the following command to add unrested
to your project.
# pnpm
pnpm add -D unrested
# npm
npm install -D unrested
# yarn
yarn add -D unrested
Usage
import { createClient } from 'unrested'
// The base URL default is `/`
const api = createClient()
unrested
inherits ofetch
's options. Refer to the documentation for a complete list of options.
import { createClient } from 'unrested'
// Set a custom base URL as needed
const api = createClient({
baseURL: 'https://jsonplaceholder.typicode.com',
})
Path Segment Chaining
Chain single path segments or path ids by a dot. You can even type the response of your request!
// GET request to <baseURL>/users
const users = await api.users.get<UserResponse>()
// For GET request you can add search params
// <baseURL>/users?search=john
const users = await api.users.get<UserResponse>({ search: 'john' })
To include dynamic API path segments, you have two options:
// Typed GET request to <baseURL>/users/1
const userId = 1
// โฆ using the chain syntax:
const user = await api.users(userId).get<UserResponse>()
// โฆ or the bracket syntax:
const user = await api.users[`${userId}`].get<UserResponse>()
HTTP Request Methods
Add the appropriate method to the end of your API call. The following methods are supported:
get()
post()
put()
delete()
patch()
Payload Requests
For HTTP request methods supporting a payload, add it to the method call:
// POST request to <baseURL>/users
const response = await api.users.post({ name: 'foo' })
ofetch
Default Options For import { createClient } from 'unrested'
const api = createClient({
baseURL: 'https://jsonplaceholder.typicode.com',
async onRequestError({ request, options, error }) {
console.log('[fetch request error]', request, error)
},
async onResponseError({ request, options, error }) {
console.log('[fetch response error]', request, error)
},
})
Override Default Options
You can add/overwrite ofetch
options on a method-level:
const response = await api.users.get({
headers: {
'Cache-Control': 'no-cache',
},
})
Credits
- Ilya Komsa for his REST API generator.
- David Wells for his GitHub API using proxies.
License
MIT License ยฉ 2022-2023 Johann Schopplich