Skip to content

JavaScript API Client Examples

This section demonstrates how to make authenticated HTTP requests in JavaScript using both the native fetch API and the popular axios library.

Both approaches use Bearer token authentication to communicate with a REST API.


Base Configuration

Before making requests, define your API configuration:

const BASE_URL = "https://website.core-software.co.uk";
const TOKEN = "YOUR_TOKEN_HERE";

⚠️ Never hardcode API tokens in production applications. Use environment variables or a secure secrets manager instead.


Option 1: Using Fetch

The fetch API is built into modern browsers and Node.js (v18+), making it the simplest way to send HTTP requests without additional dependencies.

Example Request

const BASE_URL = "https://website.core-software.co.uk";
const TOKEN = "YOUR_TOKEN_HERE";

const response = await fetch(`${BASE_URL}/api/v1`, {
    method: "GET",
    headers: {
        Authorization: `Bearer ${TOKEN}`,
        "Content-Type": "application/json",
    },
});

console.log("Status:", response.status);

const data = await response.json();

console.log("Body:", data);

Notes

  • Uses native browser and Node.js functionality
  • No external dependencies are required
  • Response errors should be handled manually using response.ok
  • Suitable for lightweight applications and simple integrations

Option 2: Using Axios

Axios is a popular HTTP client library that simplifies request handling and automatically parses JSON responses.

Installation

npm install axios

Example

import axios from "axios";

const BASE_URL = "https://website.core-software.co.uk";
const TOKEN = "YOUR_TOKEN_HERE";

const { status, data } = await axios.get(
    `${BASE_URL}/api/v1`,
    {
        headers: {
            Authorization: `Bearer ${TOKEN}`,
        },
    }
);

console.log("Status:", status);
console.log("Body:", data);

Why use Axios?

  • Automatic JSON parsing
  • Simpler error handling
  • Cleaner request configuration
  • Built-in support for interceptors and middleware

Best Practices

  • Store API tokens securely using environment variables:
process.env.API_TOKEN
  • Handle both network and HTTP errors gracefully
  • Use reusable API service modules for larger applications
  • Centralise API configuration to avoid repeating base URLs