glr-api-helper
v2.1.2
Published
Een eenvoudige helper voor API-aanvragen
Downloads
101
Readme
(MINOR) Update v2.1.0
Added default export, you can now import the module with a custom name! e.g. "import apiHelper from 'glr-api-helper';"
(PATCH) Update v2.0.2
Fixed code-breaking bug.
glr-api-helper
A tiny, ESM-friendly helper for simple HTTP requests using fetch. Provides three convenience methods: get, post, and del for common REST interactions.
Install
From npm (or add this package locally):
npm install glr-api-helperThis package uses ESM. Ensure your project uses an ESM-compatible environment.
Quick usage (ESM)
import apiHelper from 'glr-api-helper';
const baseURL = 'https://jsonplaceholder.typicode.com';
async function example() {
try {
// GET with query params
const posts = await apiHelper.get(baseURL, '/posts', { userId: 1 });
console.log('GET /posts?userId=1', posts.slice(0, 3));
// POST JSON
const newPost = await apiHelper.post(baseURL, '/posts', {
title: 'Hello',
body: 'World',
userId: 1
});
console.log('Created', newPost);
// DELETE
const deleted = await apiHelper.del(baseURL, '/posts/1');
console.log('Deleted', deleted);
} catch (err) {
console.error('API error:', err.message);
}
}
example();API
get(baseURL, endpoint, params = {})- Builds a URL from
baseURL+endpointand appendsparamsas query string. Returns parsed JSON. Throws on non-2xx responses.
- Builds a URL from
post(baseURL, endpoint, data = {})- Sends a JSON POST to
baseURL + endpointwithdataas the request body. Returns parsed JSON. Throws on non-2xx responses.
- Sends a JSON POST to
del(baseURL, endpoint)- Sends a DELETE request to
baseURL + endpoint. Returns parsed JSON. Throws on non-2xx responses.
- Sends a DELETE request to
Note: The module exports a default object containing these methods. If you prefer named variables you can destructure:
import apiHelper from 'glr-api-helper';
const { get, post, del } = apiHelper;Troubleshooting
- If you see a Node warning about module type, add
"type": "module"to yourpackage.json(this package already uses ESM). - Errors are thrown when the response status is not OK — handle them with
try/catchor.catch()when using promises.
Development / Testing
- There's a simple
test.jsincluded that demonstrates basic calls toget,post, anddelagainstjsonplaceholder.typicode.com. - Because this package exports a default object, update
test.jsif it uses named imports; either import the default and destructure or call methods on the default export.
License
ISC — feel free to modify and reuse.
