Package Exports
- @jstormes/apicize-lib
- @jstormes/apicize-lib/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@jstormes/apicize-lib) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
@jstormes/apicize-lib
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: 'john@example.com'
}
});
// 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 testAuthentication 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