1.0.2 • Published 5 months ago
@sulekaustubh/easy-api v1.0.2
easy-api
A simple wrapper around axios for easier GET API calls.
Installation
npm install easy-api
Usage
Basic Usage
import { api_get } from "easy-api";
// Simple GET request
const getData = async () => {
try {
// Just provide the endpoint
const data = await api_get("/users");
console.log(data);
} catch (error) {
console.error(error);
}
};
With Authentication
import { api_get } from "easy-api";
// GET request with authentication
const getProtectedData = async () => {
try {
// Set requiresAuth to true to use the token from localStorage
const data = await api_get("/protected-resource", true);
console.log(data);
} catch (error) {
console.error(error);
}
};
With React
import React, { useEffect, useState } from "react";
import { api_get } from "easy-api";
function UserList() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchUsers = async () => {
try {
const data = await api_get("/users", true);
setUsers(data);
} catch (err) {
setError(err.message || "Failed to fetch users");
} finally {
setLoading(false);
}
};
fetchUsers();
}, []);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
return (
<div>
<h1>Users</h1>
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
export default UserList;
API
Function
api_get(endpoint, requiresAuth, options)
Parameters
endpoint
: The API endpoint to callrequiresAuth
: Whether the request requires authentication (will use token from localStorage)options
: Additional axios options
Configuration
This package uses the following environment variables:
NEXT_PUBLIC_BACKEND_URL
: Base URL for the API
License
MIT