### Configuration File Setup Source: https://github.com/aspida/openapi2aspida/blob/main/README.md Example configuration file for customizing the generation process. ```js module.exports = { input: 'api', // "input" of aspida is "output" for openapi2aspida outputEachDir: true, // Generate $api.ts in each endpoint directory openapi: { inputFile: 'https://petstore.swagger.io/v2/swagger.json' }, }; ``` -------------------------------- ### Usage Example in TypeScript Source: https://github.com/aspida/openapi2aspida/blob/main/README.md Example implementation using the generated aspida client to perform POST and GET requests. ```ts import axiosClient from '@aspida/axios'; import api from './api/$api'; import type { Pet } from './api/@types'; (async () => { const client = api(axiosClient()); const petId = 100; const body: Pet = { id: petId, name: 'hoge', photoUrls: [], status: 'available', }; await client.pet.$post({ body }); const pet = await client.pet._petId(petId).$get(); console.log(pet); })(); ``` -------------------------------- ### Initialize and Install Dependencies Source: https://github.com/aspida/openapi2aspida/blob/main/README.md Commands to create a project directory, generate the API client from a URL or file, and install required packages. ```sh $ mkdir petstore-api $ cd petstore-api $ npx openapi2aspida -i https://petstore.swagger.io/v2/swagger.json # or ../local-swagger.yaml # api/$api.ts was built successfully. $ npm init -y $ npm install @aspida/axios axios typescript ts-node @types/node ``` -------------------------------- ### CLI Options Example Source: https://github.com/aspida/openapi2aspida/blob/main/README.md Example of running the generator with specific input and output directory flags. ```bash npx openapi2aspida -i=openApi/sample.yaml -o=lib/api/sample ``` -------------------------------- ### Run Project Source: https://github.com/aspida/openapi2aspida/blob/main/README.md Command to execute the start script and verify the output. ```sh $ npm start # { id: 100, name: 'hoge', photoUrls: [], tags: [], status: 'available' } ``` -------------------------------- ### Package Scripts Configuration Source: https://github.com/aspida/openapi2aspida/blob/main/README.md Example package.json script to execute the TypeScript file. ```json { "scripts": { "start": "ts-node index.ts" } } ``` -------------------------------- ### Aspida Client Usage for File Uploads Source: https://context7.com/aspida/openapi2aspida/llms.txt Demonstrates how to use the generated Aspida client to upload files. Includes examples for uploading a binary file using a read stream and uploading with FormData, appending fields. ```typescript // Usage with generated client import type { ReadStream } from 'fs'; import fs from 'fs'; // Upload binary file const fileStream: ReadStream = fs.createReadStream('./document.pdf'); await client.file._id(123).upload.$post({ body: fileStream, query: { path: '/documents/uploads' } }); // Upload with FormData const formData = new FormData(); formData.append('file', file); formData.append('description', 'Important document'); await client.documents.$post({ body: { file: fileBuffer, // File | ReadStream description: 'Monthly report' } }); ``` -------------------------------- ### Generated Endpoint Method Definitions (Pet API) Source: https://context7.com/aspida/openapi2aspida/llms.txt These TypeScript files define the HTTP methods, parameters, request bodies, and response types for specific API endpoints using aspida's DefineMethods type. This example shows definitions for a single pet endpoint. ```typescript // Generated file: api/pet/_petId@number/index.ts /* eslint-disable */ import type { DefineMethods } from 'aspida'; import type * as Types from '../../@types'; export type Methods = DefineMethods<{ /** Returns a single pet */ get: { status: 200; resBody: Types.Pet; }; /** Updates a pet in the store with form data */ post: { status: 200; reqFormat: URLSearchParams; reqBody: { name?: string | undefined; status?: string | undefined; }; }; delete: { status: 200; reqHeaders?: { api_key?: string | undefined; } | undefined; }; }>; ``` -------------------------------- ### Generated Endpoint Method Definitions (Find Pet by Status) Source: https://context7.com/aspida/openapi2aspida/llms.txt This TypeScript file defines the HTTP GET method for the /pet/findByStatus endpoint, including query parameters for filtering by status and the expected response body. ```typescript // Generated file: api/pet/findByStatus/index.ts export type Methods = DefineMethods<{ get: { status: 200; query: { /** Status values for filtering */ status: ('available' | 'pending' | 'sold')[]; }; resBody: Types.Pet[]; }; }>; ``` -------------------------------- ### Build from Config Source: https://github.com/aspida/openapi2aspida/blob/main/README.md Command to run the generator using the configuration file. ```sh $ npx openapi2aspida ``` -------------------------------- ### Defining Configuration Files Source: https://context7.com/aspida/openapi2aspida/llms.txt Batch process multiple API specifications using a JavaScript configuration file. ```javascript // aspida.config.js module.exports = [ { input: 'api/petstore', // Output directory for generated code outputEachDir: true, // Generate $api.ts in each endpoint directory trailingSlash: false, // URL trailing slash handling openapi: { inputFile: 'https://petstore.swagger.io/v2/swagger.json', // OpenAPI spec URL or path yaml: false, // Force YAML parsing (auto-detected if omitted) outputDir: 'api/petstore' // Override output directory } }, { input: 'api/internal', outputEachDir: true, openapi: { inputFile: './specs/internal-api.yaml' } } ]; // Run with: npx openapi2aspida ``` -------------------------------- ### CLI Usage for OpenAPI 2 Aspida Source: https://context7.com/aspida/openapi2aspida/llms.txt Common command-line operations for generating API clients from URLs or local files. ```bash # Basic usage - convert from URL npx openapi2aspida -i https://petstore.swagger.io/v2/swagger.json # Convert from local file npx openapi2aspida -i ./api/openapi.yaml # Specify output directory npx openapi2aspida -i ./api/swagger.json -o ./src/api # Use config file npx openapi2aspida -c ./aspida.config.js # Check version npx openapi2aspida --version ``` -------------------------------- ### OpenAPI Spec for File Upload Source: https://context7.com/aspida/openapi2aspida/llms.txt Defines POST endpoints for uploading binary files and multipart form data. The first endpoint handles binary uploads with an ID and an optional path query parameter. The second handles multipart form data with a 'file' and 'description' field. ```yaml paths: /file/{id}/upload: post: parameters: - in: path name: id schema: type: integer required: true - in: query name: path schema: type: string requestBody: content: application/octet-stream: schema: type: string format: binary responses: '204': description: No Content /documents: post: requestBody: content: multipart/form-data: schema: type: object properties: file: type: string format: binary description: type: string responses: '200': description: Success ``` -------------------------------- ### Using the Generated API Client Source: https://context7.com/aspida/openapi2aspida/llms.txt Perform type-safe HTTP requests using the generated client with supported adapters like axios or fetch. ```typescript import axiosClient from '@aspida/axios'; import api from './api/$api'; import type { Pet, Order } from './api/@types'; // Initialize client const client = api(axiosClient()); // GET request with path parameter const pet = await client.pet._petId(123).$get(); console.log(pet.name, pet.status); // GET request with query parameters const pets = await client.pet.findByStatus.$get({ query: { status: ['available', 'pending'] } }); // POST request with body const newPet: Pet = { id: 100, name: 'Buddy', photoUrls: ['https://example.com/photo.jpg'], status: 'available' }; await client.pet.$post({ body: newPet }); // PUT request with path params and body await client.pet._petId(100).$put({ body: { ...newPet, name: 'Updated Buddy' } }); // DELETE request await client.pet._petId(100).$delete(); // File upload with multipart/form-data await client.pet._petId(100).uploadImage.$post({ body: { file: imageFile, additionalMetadata: 'Profile photo' } }); // Access URL path directly const petUrl = client.pet._petId(100).$path(); // => '/pet/100' // With query string in path const searchUrl = client.pet.findByStatus.$path({ method: 'get', query: { status: ['available'] } }); // => '/pet/findByStatus?status=available' ``` -------------------------------- ### Advanced Schema Features Source: https://context7.com/aspida/openapi2aspida/llms.txt Demonstrates the use of advanced OpenAPI 3.0 schema features like oneOf, allOf, and nullable types, and their corresponding TypeScript representations. ```APIDOC ## OpenAPI 3.0 Schema Features Supports advanced OpenAPI 3.0 schema features including oneOf, allOf, anyOf, nullable types, and enum definitions with full TypeScript representation. ### Components Schemas #### Response Schema ```yaml components: schemas: Response: oneOf: - $ref: '#/components/schemas/SuccessResponse' - $ref: '#/components/schemas/ErrorResponse' ``` #### Pet Schema ```yaml components: schemas: Pet: allOf: - $ref: '#/components/schemas/BaseEntity' - type: object required: - name properties: name: type: string breed: type: string nullable: true ``` #### Status Enum ```yaml components: schemas: Status: type: string enum: - active - inactive - pending ``` ### Generated TypeScript Types #### Response Type ```typescript export type Response = Types.SuccessResponse | Types.ErrorResponse; ``` #### Pet Type ```typescript export type Pet = Types.BaseEntity & { name: string; breed?: string | null | undefined; } ``` #### Status Type ```typescript export type Status = 'active' | 'inactive' | 'pending'; ``` ### Usage Example ```typescript const handleResponse = (res: Types.Response) => { if ('error' in res) { console.error(res.error.message); } else { console.log(res.data); } }; ``` ``` -------------------------------- ### OpenAPI Specification with External References Source: https://context7.com/aspida/openapi2aspida/llms.txt This OpenAPI YAML defines API paths and uses external references ($ref) to include parameter and schema definitions from other files and URLs. aspida automatically fetches and merges these external schemas. ```yaml # main-api.yaml openapi: "3.0.0" info: title: "Main API" version: "1.0" paths: /users/{user_id}/orders: get: parameters: - $ref: './common/parameters.yaml#/UserId' responses: '200': content: application/json: schema: type: array items: $ref: 'https://api.example.com/schemas/order.json#/Order' # The tool automatically fetches and resolves: # - ./common/parameters.yaml # - https://api.example.com/schemas/order.json # And generates unified TypeScript types ``` -------------------------------- ### File Upload API Source: https://context7.com/aspida/openapi2aspida/llms.txt Endpoints for uploading files, including binary uploads and multipart/form-data uploads with additional fields. ```APIDOC ## POST /file/{id}/upload ### Description Uploads a file to a specific resource identified by its ID. ### Method POST ### Endpoint /file/{id}/upload ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the resource to upload the file to. #### Query Parameters - **path** (string) - Optional - The path to store the uploaded file. #### Request Body - **body** (binary) - Required - The file content to upload. ### Response #### Success Response (204) Description: No Content ``` ```APIDOC ## POST /documents ### Description Uploads a document with an associated description. ### Method POST ### Endpoint /documents ### Parameters #### Request Body - **file** (binary) - Required - The document file to upload. - **description** (string) - Optional - A description for the document. ``` -------------------------------- ### Programmatic API Generation Source: https://context7.com/aspida/openapi2aspida/llms.txt Integrate code generation directly into Node.js build pipelines using the build function. ```typescript import build from 'openapi2aspida'; import type { ConfigFile } from 'openapi2aspida/dist/getConfig'; // Single configuration const config: ConfigFile = { input: 'src/api', outputEachDir: true, openapi: { inputFile: 'https://api.example.com/openapi.json' } }; // Execute build - returns array of promises const results = build(config); await Promise.all(results); console.log('API client generated successfully'); // Multiple configurations const configs: ConfigFile[] = [ { input: 'src/api/users', openapi: { inputFile: './specs/users.yaml' } }, { input: 'src/api/products', openapi: { inputFile: './specs/products.yaml' } } ]; await Promise.all(build(configs).flat()); ``` -------------------------------- ### OpenAPI Spec with Advanced Schemas Source: https://context7.com/aspida/openapi2aspida/llms.txt Showcases advanced OpenAPI 3.0 schema features including oneOf, allOf, and enum definitions. These allow for complex data structures and type definitions. ```yaml # OpenAPI spec with advanced schemas components: schemas: Response: oneOf: - $ref: '#/components/schemas/SuccessResponse' - $ref: '#/components/schemas/ErrorResponse' Pet: allOf: - $ref: '#/components/schemas/BaseEntity' - type: object required: - name properties: name: type: string breed: type: string nullable: true Status: type: string enum: - active - inactive - pending ``` -------------------------------- ### Generated TypeScript Types for Advanced Schemas Source: https://context7.com/aspida/openapi2aspida/llms.txt Illustrates the TypeScript types generated by Aspida for OpenAPI schemas. Includes union types for 'oneOf', intersection types for 'allOf', and literal types for 'enum'. ```typescript // Generated TypeScript types export type Response = Types.SuccessResponse | Types.ErrorResponse; export type Pet = Types.BaseEntity & { name: string; breed?: string | null | undefined; } export type Status = 'active' | 'inactive' | 'pending'; // Usage const handleResponse = (res: Types.Response) => { if ('error' in res) { console.error(res.error.message); } else { console.log(res.data); } }; ``` -------------------------------- ### Generated TypeScript Types for External References Source: https://context7.com/aspida/openapi2aspida/llms.txt These TypeScript types are generated after aspida resolves and merges external $ref references from OpenAPI specifications. They represent the combined schemas, including parameters and data models from different sources. ```typescript // Generated types include external references // api/@types/index.ts export type External0_UserId = { name: 'user_id'; in: 'path'; required: true; schema: { type: 'string' }; } export type External1_Order = { id: number; userId: string; items: OrderItem[]; total: number; } ``` -------------------------------- ### Generated TypeScript Type Definitions Source: https://context7.com/aspida/openapi2aspida/llms.txt These TypeScript interfaces are automatically generated from OpenAPI component schemas, ensuring type safety for request and response data. They are located in the api/@types/index.ts file. ```typescript // Generated from OpenAPI components/schemas // Located in: api/@types/index.ts /* eslint-disable */ /** Customer */ export type Customer = { /** ID */ id?: number | undefined; /** NAME */ name?: string | undefined; /** Type of pet 1:dog 2:cat 3:other */ pet?: 1 | 2 | 3 | undefined; } /** Pet model with required fields */ export type Pet = { id: number; name: string; category?: Category | undefined; photoUrls: string[]; tags?: Tag[] | undefined; /** pet status in the store */ status?: 'available' | 'pending' | 'sold' | undefined; } /** Order for purchasing a pet */ export type Order = { id?: number | undefined; petId?: number | undefined; quantity?: number | undefined; shipDate?: string | undefined; status?: 'placed' | 'approved' | 'delivered' | undefined; complete?: boolean | undefined; } // Usage in application code import type { Pet, Order, Customer } from './api/@types'; const createPet = (data: Partial): Pet => ({ id: data.id ?? 0, name: data.name ?? '', photoUrls: data.photoUrls ?? [], ...data }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.