npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@jstormes/apicize-lib

v1.1.0

Published

Core library for Apicize tools - TypeScript types, utilities, and runtime support for API testing

Readme

@jstormes/apicize-lib

npm version License: MIT TypeScript npm downloads

Core library for Apicize tools - provides TypeScript types, utilities, and runtime support for API testing with .apicize files.

📦 Installation

npm install @jstormes/apicize-lib
# or
yarn add @jstormes/apicize-lib
# or
pnpm add @jstormes/apicize-lib

🚀 Quick Start

import {
    ApicizeFile,
    ApicizeRequest,
    BodyType,
    TestContext,
    RequestExecutor,
    VariableEngine
} from '@jstormes/apicize-lib';

// Parse and validate .apicize files
const validator = new ApicizeValidator();
const result = await validator.validate('api-test.apicize');

// Execute requests with test context
const executor = new RequestExecutor();
const response = await executor.execute({
    url: 'https://api.example.com/users',
    method: 'GET',
    headers: { 'Authorization': 'Bearer token' }
});

// Use in generated tests
describe('API Test', () => {
    let response: ApicizeResponse;

    beforeEach(async () => {
        response = await context.execute(request);
    });

    it('should return success', () => {
        expect(response.status).to.equal(200);

        const JSON_body = (response.body.type === BodyType.JSON)
            ? response.body.data
            : expect.fail('Response not JSON');

        output('userId', JSON_body.id);
    });
});

📚 Core Components

Types and Interfaces

// Main file structure
interface ApicizeFile {
    version: number;
    requests: (ApicizeRequest | ApicizeRequestGroup)[];
    scenarios: ApicizeScenario[];
    authorizations: ApicizeAuthorization[];
    defaults: ApicizeDefaults;
}

// Request definition
interface ApicizeRequest {
    id: string;
    name: string;
    url: string;
    method: HttpMethod;
    test?: string;
    headers?: NameValuePair[];
    body?: ApicizeBody;
    queryStringParams?: NameValuePair[];
}

// Response structure
interface ApicizeResponse {
    status: number;
    headers: Record<string, string>;
    body: {
        type: BodyType;
        data: any;
    };
    timing: ResponseTiming;
}

Validation

import { ApicizeValidator, ValidationResult } from '@jstormes/apicize-lib';

const validator = new ApicizeValidator();

// Validate single file
const result: ValidationResult = await validator.validate('test.apicize');
if (!result.valid) {
    console.error('Validation errors:', result.errors);
}

// Validate with options
const strictResult = await validator.validate('test.apicize', {
    strict: true,
    autoFix: true,
    schemaVersion: '1.0'
});

Request Execution

import { RequestExecutor, ExecutionOptions } from '@jstormes/apicize-lib';

const executor = new RequestExecutor();

// Basic execution
const response = await executor.execute({
    url: 'https://api.example.com/users',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: {
        name: 'John Doe',
        email: '[email protected]'
    }
});

// With options
const responseWithOptions = await executor.execute(request, {
    timeout: 30000,
    followRedirects: true,
    validateSSL: false,
    proxy: 'http://proxy.example.com:8080'
});

Variable Substitution

import { VariableEngine } from '@jstormes/apicize-lib';

const engine = new VariableEngine();

// Set variables
engine.setVariables({
    baseUrl: 'https://api.example.com',
    apiKey: 'secret-key',
    userId: 123
});

// Substitute in strings
const url = engine.substitute('{{baseUrl}}/users/{{userId}}');
// Result: 'https://api.example.com/users/123'

// Substitute in objects
const body = engine.substituteObject({
    user: '{{userId}}',
    key: '{{apiKey}}'
});

Test Context

import { TestContext, TestHelper } from '@jstormes/apicize-lib';

// In test setup
const helper = new TestHelper();
const context = await helper.setupTest('test-name', {
    scenario: 'production',
    variables: {
        baseUrl: 'https://api.example.com'
    }
});

// Access context in tests
const response = await context.execute(request);
const variables = context.$; // Access variables
context.output('key', 'value'); // Pass data to next test

Authentication Handlers

import {
    AuthManager,
    BasicAuth,
    OAuth2Client,
    ApiKeyAuth
} from '@jstormes/apicize-lib';

const authManager = new AuthManager();

// Register auth providers
authManager.register('basic', new BasicAuth({
    username: 'user',
    password: 'pass'
}));

authManager.register('oauth', new OAuth2Client({
    accessTokenUrl: 'https://auth.example.com/token',
    clientId: 'client-id',
    clientSecret: 'client-secret'
}));

// Apply authentication to request
const headers = await authManager.applyAuth('oauth', request);

Data Handling

import {
    DataLoader,
    CsvParser,
    JsonParser
} from '@jstormes/apicize-lib';

// Load CSV data
const csvLoader = new DataLoader();
const csvData = await csvLoader.loadCsv('data/users.csv');

// Load JSON data
const jsonData = await csvLoader.loadJson('data/config.json');

// Iterate data for tests
for (const row of csvData) {
    await runTestWithData(row);
}

🔧 Utilities

Path Utilities

import { PathUtils } from '@jstormes/apicize-lib';

// Resolve paths
const absolutePath = PathUtils.resolve('./relative/path');

// Ensure directory exists
await PathUtils.ensureDir('./output/directory');

// Find project root
const projectRoot = PathUtils.findProjectRoot();

String Utilities

import { StringUtils } from '@jstormes/apicize-lib';

// Generate IDs
const uuid = StringUtils.generateId();

// Sanitize filenames
const safeName = StringUtils.sanitizeFilename('my:file?.txt');

// Template processing
const result = StringUtils.processTemplate('Hello {{name}}', { name: 'World' });

Validation Schemas

import { Schemas } from '@jstormes/apicize-lib';

// Get schema for validation
const requestSchema = Schemas.getRequestSchema();
const fileSchema = Schemas.getApicizeFileSchema();

// Custom validation
const isValid = Schemas.validate(data, requestSchema);

🎯 Error Handling

import {
    ApicizeError,
    ValidationError,
    ExecutionError,
    ParseError
} from '@jstormes/apicize-lib';

try {
    const result = await validator.validate(file);
} catch (error) {
    if (error instanceof ValidationError) {
        console.error('Validation failed:', error.errors);
    } else if (error instanceof ExecutionError) {
        console.error('Execution failed:', error.request, error.response);
    } else if (error instanceof ParseError) {
        console.error('Parse failed:', error.file, error.line);
    }
}

📊 Types Reference

Body Types

enum BodyType {
    None = 'None',
    Text = 'Text',
    JSON = 'JSON',
    XML = 'XML',
    Form = 'Form',
    Raw = 'Raw'
}

HTTP Methods

type HttpMethod =
    | 'GET'
    | 'POST'
    | 'PUT'
    | 'DELETE'
    | 'PATCH'
    | 'HEAD'
    | 'OPTIONS';

Authorization Types

type AuthorizationType =
    | 'Basic'
    | 'OAuth2Client'
    | 'OAuth2Pkce'
    | 'ApiKey';

🧪 Testing Support

The library provides comprehensive support for test generation:

// Test runtime globals
declare global {
    var response: ApicizeResponse;
    var $: Record<string, any>;
    function output(key: string, value: any): void;
}

// In generated tests
it('should validate response', () => {
    expect(response.status).to.equal(200);

    const JSON_body = (response.body.type === BodyType.JSON)
        ? response.body.data
        : expect.fail('Expected JSON response');

    expect(JSON_body.id).to.exist;
    output('userId', JSON_body.id); // Available in next test as $.userId
});

📦 Exports

The library exports the following modules:

// Main exports
export * from './types';
export * from './validation';
export * from './execution';
export * from './variables';
export * from './auth';
export * from './data';
export * from './utils';
export * from './errors';

// Test support
export * from './testing/context';
export * from './testing/helpers';
export * from './testing/assertions';

🔗 Integration

With Mocha/Chai

import { expect } from 'chai';
import { TestHelper, BodyType } from '@jstormes/apicize-lib';

describe('API Tests', function() {
    const helper = new TestHelper();

    beforeEach(async function() {
        this.context = await helper.setupTest(this.currentTest.title);
    });

    it('should test API', async function() {
        const response = await this.context.execute(request);
        expect(response.status).to.equal(200);
    });
});

With Jest

import { TestHelper, BodyType } from '@jstormes/apicize-lib';

describe('API Tests', () => {
    let context;

    beforeEach(async () => {
        const helper = new TestHelper();
        context = await helper.setupTest('test-name');
    });

    test('should test API', async () => {
        const response = await context.execute(request);
        expect(response.status).toBe(200);
    });
});

📄 License

MIT © Apicize Tools

🔗 Links