### Install openapi-typescript Source: https://openapi-ts.dev/6.x/node Installs the openapi-typescript package as a development dependency using npm. ```bash npm i --save-dev openapi-typescript ``` -------------------------------- ### Install openapi-typescript CLI Source: https://openapi-ts.dev/6.x/introduction Installs the openapi-typescript package as a development dependency using npm. This command is typically run in a Node.js project. ```bash npm i -D openapi-typescript ``` -------------------------------- ### OpenAPI Schema `additionalProperties` to TypeScript Type Source: https://openapi-ts.dev/6.x/advanced Demonstrates how to use `additionalProperties` in OpenAPI schemas to generate specific TypeScript types. It shows examples for `any`, `unknown`, and typed properties, highlighting the best practice of defining the type for `additionalProperties`. ```yaml type: object ``` ```yaml type: object additionalProperties: true ``` ```yaml type: object additionalProperties: type: string ``` -------------------------------- ### Load OpenAPI Schema with Node.js API Source: https://openapi-ts.dev/6.x/node Demonstrates how to use the openapi-typescript Node.js API to generate TypeScript types from an OpenAPI schema. It shows examples of loading schemas from a JSON object in memory, a local file (YAML or JSON), and a remote URL. ```javascript import fs from "node:fs"; import openapiTS from "openapi-typescript"; // example 1: load [object] as schema (JSON only) const schema = await fs.promises.readFile("spec.json", "utf8"); // must be OpenAPI JSON const output = await openapiTS(JSON.parse(schema)); // example 2: load [string] as local file (YAML or JSON; released in v4.0) const localPath = new URL("./spec.yaml", import.meta.url); // may be YAML or JSON format const output = await openapiTS(localPath); // example 3: load [string] as remote URL (YAML or JSON; released in v4.0) const output = await openapiTS("https://myurl.com/v1/openapi.yaml"); ``` -------------------------------- ### Define Custom Enum Names and Descriptions in OpenAPI Source: https://openapi-ts.dev/6.x/advanced This YAML example demonstrates how to use `x-enum-varnames` and `x-enum-descriptions` to define custom enum names and descriptions for OpenAPI schema values. These extensions are used to generate code with specific enum item names and comments, improving code readability and maintainability. ```YAML ErrorCode: type: integer format: int32 enum: - 100 - 200 - 300 x-enum-varnames: - Unauthorized - AccessDenied - Unknown x-enum-descriptions: - "User is not authorized" - "User has no access to this resource" - "Something went wrong" ``` -------------------------------- ### OpenAPI `$defs` with Object Types to TypeScript Source: https://openapi-ts.dev/6.x/advanced Demonstrates the correct usage of `$defs` within object types in OpenAPI schemas to ensure proper TypeScript type generation. It shows a working example where `$ref` correctly points to a definition within `$defs`. ```yaml components: schemas: DefType: type: object $defs: myDefType: type: string MyType: type: object properties: myType: $ref: "#/components/schemas/DefType/$defs/myDefType" ``` -------------------------------- ### TypeScript Enum Generation from OpenAPI Extensions Source: https://openapi-ts.dev/6.x/advanced This TypeScript code shows the output generated from the YAML example using `x-enum-varnames` and `x-enum-descriptions`. It defines an enum `ErrorCode` with specific values, custom names, and corresponding comments, illustrating how OpenAPI extensions translate into typed code. ```TypeScript enum ErrorCode { // User is not authorized Unauthorized = 100 // User has no access to this resource AccessDenied = 200 // Something went wrong Unknown = 300 } ``` -------------------------------- ### TypeScript: Path Params as Types Source: https://openapi-ts.dev/6.x/cli Demonstrates how the `--path-params-as-types` option in openapi-typescript allows for dynamic string lookups on the `paths` object, enabling more flexible type inference for URL parameters. ```typescript export interface paths { "/user/{user_id}": components["schemas"]["User"]; } ``` ```typescript import type { paths } from "./api/v1"; const url = `/user/${id}`; type UserResponses = paths["/user/{user_id}"]["responses"]; ``` ```typescript import type { paths } from "./api/v1"; const url = `/user/${id}`; type UserResponses = paths[url]["responses"]; // automatically matches `paths['/user/{user_id}']` ``` -------------------------------- ### Import generated types in TypeScript Source: https://openapi-ts.dev/6.x/introduction Demonstrates how to import and use the TypeScript types generated by openapi-typescript. It shows how to access schema components, path parameters, and response schemas. ```typescript import type { paths, components } from "./api/v1"; // generated by openapi-typescript // Schema Obj type MyType = components["schemas"]["MyType"]; // Path params type EndpointParams = paths["/my/endpoint"]["parameters"]; // Response obj type SuccessResponse = paths["/my/endpoint"]["get"]["responses"][200]["content"]["application/json"]["schema"]; type ErrorResponse = paths["/my/endpoint"]["get"]["responses"][500]["content"]["application/json"]["schema"]; ``` -------------------------------- ### CLI: Parse Local Schema Source: https://openapi-ts.dev/6.x/cli Parses a local YAML schema file and outputs a TypeScript file. This is the most common way to use the openapi-typescript CLI. ```bash npx openapi-typescript schema.yaml -o schema.ts # πŸš€ schema.yaml -> schema.ts [7ms] ``` -------------------------------- ### OpenAPI Schema `additionalProperties` to TypeScript Type Source: https://openapi-ts.dev/6.x/advanced Shows the corresponding TypeScript types generated by openapi-typescript for different `additionalProperties` configurations in OpenAPI schemas. It illustrates the progression from `Record` to `Record` and finally to `Record`. ```typescript Record; ``` ```typescript Record; ``` ```typescript Record; ``` -------------------------------- ### Typechecking API Mocks with openapi-typescript (TypeScript) Source: https://openapi-ts.dev/6.x/advanced This snippet shows how to write a helper function using openapi-typescript to typecheck API mocks against an OpenAPI schema. It leverages generated types to ensure the correct data shape for paths, HTTP methods, and status codes, using vitest and fetch-mock. ```ts import { mockResponses } from "../test/utils"; describe("My API test", () => { it("mocks correctly", async () => { mockResponses({ "/users/{user_id}": { // βœ… Correct 200 response get: { status: 200, body: { id: "user-id", name: "User Name" } }, // βœ… Correct 403 response delete: { status: 403, body: { code: "403", message: "Unauthorized" } }, }, "/users": { // βœ… Correct 201 response put: { 201: { status: "success" } }, }, }); // test 1: GET /users/{user_id}: 200 await fetch("/users/user-123"); // test 2: DELETE /users/{user_id}: 403 await fetch("/users/user-123", { method: "DELETE" }); // test 3: PUT /users: 200 await fetch("/users", { method: "PUT", body: JSON.stringify({ id: "new-user", name: "New User" }), }); // test cleanup fetchMock.resetMocks(); }); }); ``` -------------------------------- ### Data Fetching with openapi-fetch Source: https://openapi-ts.dev/6.x/advanced Demonstrates safe and simple data fetching using an automatically-typed fetch wrapper. openapi-fetch is recommended for its type safety and ease of use, avoiding generics to prevent hidden errors. ```TypeScript import OpenAPI from "openapi-fetch"; import type { paths } from "./api.types"; // Assuming your generated types are here const client = OpenAPI({ baseUrl: "https://api.example.com", }); async function getUsers() { const { data, error } = await client.get("/users", { params: { query: { limit: 10 } } }); if (error) { console.error("Error fetching users:", error); return; } console.log("Users:", data); } ``` -------------------------------- ### TypeScript: Support Array Length Source: https://openapi-ts.dev/6.x/cli Illustrates how the `--support-array-length` option generates tuple types for arrays with specified `minItems` or `maxItems` in the OpenAPI schema, providing stricter type checking. ```typescript export interface components { schemas: { - TupleType: string[]; + TupleType: [string] | [string, string]; }; } ``` -------------------------------- ### OpenAPI Schema Tuple Types to TypeScript Type Source: https://openapi-ts.dev/6.x/advanced Illustrates how to represent tuple types in OpenAPI schemas for accurate TypeScript generation. It contrasts less effective methods with the recommended approach using `maxItems`, `minItems`, or `prefixItems` to define fixed-size arrays. ```yaml type: array ``` ```yaml type: array items: type: number ``` ```yaml type: array items: type: number maxItems: 2 minItems: 2 ``` ```yaml type: array items: type: number prefixItems: - number - number ``` -------------------------------- ### CLI: Glob Local Schemas Source: https://openapi-ts.dev/6.x/cli Parses multiple local YAML schema files using globbing patterns and outputs them into a specified directory. This is useful for projects with many schema files. ```bash npx openapi-typescript "specs/**/*.yaml" -o schemas/ # πŸš€ specs/one.yaml -> schemas/specs/one.ts [7ms] # πŸš€ specs/two.yaml -> schemas/specs/two.ts [7ms] # πŸš€ specs/three.yaml -> schemas/specs/three.ts [7ms] ``` -------------------------------- ### CLI: Parse Remote Schema Source: https://openapi-ts.dev/6.x/cli Parses a remote OpenAPI schema from a URL and outputs the generated TypeScript definitions. Supports basic authentication for private schemas. ```bash npx openapi-typescript https://petstore3.swagger.io/api/v3/openapi.yaml -o petstore.d.ts # πŸš€ https://petstore3.swagger.io/api/v3/openapi.yaml -> petstore.d.ts [250ms] ``` -------------------------------- ### Transform Blob Types with openapi-typescript Source: https://openapi-ts.dev/6.x/node Demonstrates using the `transform` option with openapi-typescript to handle schema properties formatted as 'binary' (often used for file uploads), converting them to the `Blob` type in TypeScript. ```typescript const types = openapiTS(mySchema, { transform(schemaObject, metadata): string { if ("format" in schemaObject && schemaObject.format === "binary") { return schemaObject.nullable ? "Blob | null" : "Blob"; } }, }); ``` -------------------------------- ### Define Pet Union with Schema References (YAML) Source: https://openapi-ts.dev/6.x/advanced This YAML snippet defines a base 'Pet' schema that is a union of several other schemas (Cat, Dog, Rabbit, Snake, Turtle) using `oneOf`. It also defines common properties for pets and a specific 'Cat' schema using `allOf` to inherit common properties and add a specific 'type' enum. ```yaml Pet: oneOf: - $ref: "#/components/schemas/Cat" - $ref: "#/components/schemas/Dog" - $ref: "#/components/schemas/Rabbit" - $ref: "#/components/schemas/Snake" - $ref: "#/components/schemas/Turtle" PetCommonProperties: type: object properties: name: type: string Cat: allOf: - "$ref": "#/components/schemas/PetCommonProperties" type: type: string enum: - cat ``` -------------------------------- ### OpenAPI Schema Tuple Types to TypeScript Type Source: https://openapi-ts.dev/6.x/advanced Presents the TypeScript types generated by openapi-typescript for various OpenAPI schema definitions of tuple types. It shows how `unknown[]` and `number[]` are generated for less specific schemas, while `[number, number]` is produced for correctly defined tuples. ```typescript unknown[] ``` ```typescript number[] ``` ```typescript [number, number]; ``` -------------------------------- ### Generate TypeScript types from OpenAPI schema Source: https://openapi-ts.dev/6.x/introduction Generates TypeScript type definition files from OpenAPI schemas. It supports both local file paths and remote URLs for the schema. The output is saved to a specified file. ```bash # Local schema npx openapi-typescript ./path/to/my/schema.yaml -o ./path/to/my/schema.d.ts # πŸš€ ./path/to/my/schema.yaml -> ./path/to/my/schema.d.ts [7ms] # Remote schema npx openapi-typescript https://myapi.dev/api/v1/openapi.yaml -o ./path/to/my/schema.d.ts # πŸš€ https://myapi.dev/api/v1/openapi.yaml -> ./path/to/my/schema.d.ts [250ms] ``` -------------------------------- ### Data Fetching with openapi-typescript-fetch Source: https://openapi-ts.dev/6.x/advanced An alternative approach to data fetching using the openapi-typescript-fetch library. This method also provides type safety for API requests. ```TypeScript import createClient from "openapi-typescript-fetch"; import type { paths } from "./api.types"; // Assuming your generated types are here const client = createClient({ baseUrl: "https://api.example.com", }); async function getProducts() { const response = await client.fetch("/products", { params: { query: { category: "electronics" } } }); if (!response.ok) { console.error(`HTTP error! status: ${response.status}`); return; } const data = await response.json(); console.log("Products:", data); } ``` -------------------------------- ### Mocking Responses with Type Safety (TypeScript) Source: https://openapi-ts.dev/6.x/advanced This utility function `mockResponses` mocks fetch calls and provides type safety against an OpenAPI schema. It takes an object mapping paths and methods to mocked responses, ensuring that the status codes and response bodies conform to the schema. ```ts import type { paths } from "./api/v1"; // generated by openapi-typescript // Settings // ⚠️ Important: change this! This prefixes all URLs const BASE_URL = "https://myapi.com/v1"; // End Settings // type helpers β€” ignore these; these just make TS lookups better type FilterKeys = { [K in keyof Obj]: K extends Matchers ? Obj[K] : never; }[keyof Obj]; type PathResponses = T extends { responses: any } ? T["responses"] : unknown; type OperationContent = T extends { content: any } ? T["content"] : unknown; type MediaType = `${string}/${string}`; type MockedResponse = FilterKeys, MediaType> extends never ? { status: Status; body?: never } : { status: Status; body: FilterKeys, MediaType>; }; /** * Mock fetch() calls and type against OpenAPI schema */ export function mockResponses(responses: { [Path in keyof Partial]: { [Method in keyof Partial]: MockedResponse< PathResponses >; }; }) { fetchMock.mockResponse((req) => { const mockedPath = findPath( req.url.replace(BASE_URL, ""), Object.keys(responses) )!; // note: we get lazy with the types here, because the inference is bad anyway and this has a `void` return signature. The important bit is the parameter signature. if (!mockedPath || (!(responses as any)[mockedPath])) throw new Error(`No mocked response for ${req.url}`); // throw error if response not mocked (remove or modify if you’d like different behavior) const method = req.method.toLowerCase(); if (!(responses as any)[mockedPath][method]) throw new Error(`${req.method} called but not mocked on ${mockedPath}`); // likewise throw error if other parts of response aren’t mocked if (!(responses as any)[mockedPath][method]) { throw new Error(`${req.method} called but not mocked on ${mockedPath}`); } const { status, body } = (responses as any)[mockedPath][method]; return { status, body: JSON.stringify(body) }; }); } // helper function that matches a realistic URL (/users/123) to an OpenAPI path (/users/{user_id}) export function findPath( actual: string, testPaths: string[] ): string | undefined { const url = new URL( actual, actual.startsWith("http") ? undefined : "http://testapi.com" ); const actualParts = url.pathname.split("/"); for (const p of testPaths) { let matched = true; const testParts = p.split("/"); if (actualParts.length !== testParts.length) continue; // automatically not a match if lengths differ for (let i = 0; i < testParts.length; i++) { if (testParts[i]!.startsWith("{")) continue; // path params ({user_id}) always count as a match if (actualParts[i] !== testParts[i]) { matched = false; break; } } if (matched) return p; } } ``` -------------------------------- ### Transform Date Types with openapi-typescript Source: https://openapi-ts.dev/6.x/node Shows how to use the `transform` option in the openapi-typescript Node.js API to customize the output for schema properties with the 'date-time' format, converting them to the `Date` type in TypeScript. ```javascript const types = openapiTS(mySchema, { transform(schemaObject, metadata): string { if ("format" in schemaObject && schemaObject.format === "date-time") { return schemaObject.nullable ? "Date | null" : "Date"; } }, }); ``` -------------------------------- ### Generate Type-Safe Mock Responses with OpenAPI TypeScript Source: https://openapi-ts.dev/6.x/advanced This TypeScript function signature, `mockResponses`, is central to generating type-safe mock data based on your OpenAPI schema. It ensures that all mock data is correctly type-checked, contributing to resilient and accurate tests. The structure directly reflects the OpenAPI design. ```TypeScript export function mockResponses(responses: { [Path in keyof Partial]: { [Method in keyof Partial]: MockedResponse< PathResponses >; }; }); ``` -------------------------------- ### Generated TypeScript Types for Pet Union Source: https://openapi-ts.dev/6.x/advanced This TypeScript code shows the generated types from the OpenAPI schema. The 'Pet' type is a union of the referenced schemas, and the 'Cat' type is an intersection of the common properties and its specific type discriminator. ```typescript Pet: components["schemas"]["Cat"] | components["schemas"]["Dog"] | components["schemas"]["Rabbit"] | components["schemas"]["Snake"] | components["schemas"]["Turtle"]; Cat: { type?: "cat"; } & components["schemas"]["PetCommonProperties"]; ``` -------------------------------- ### OpenAPI `$defs` with Object Types to TypeScript Source: https://openapi-ts.dev/6.x/advanced Illustrates the resulting TypeScript interface generated from an OpenAPI schema where `$defs` are correctly used within an object type. It shows how the `$ref` is resolved to the specific type defined in `$defs`. ```typescript export interface components { schemas: { DefType: { $defs: { myDefType: string; }; }; MyType: { myType?: components["schemas"]["DefType"]["$defs"]["myDefType"]; }; }; } ``` -------------------------------- ### OpenAPI `oneOf` Usage for TypeScript Unions Source: https://openapi-ts.dev/6.x/advanced Explains the recommended practice for using `oneOf` in OpenAPI schemas to generate TypeScript union types. It advises against combining `oneOf` with other composition methods or properties to avoid complex type generation. ```yaml Pet: type: object properties: type: type: string enum: - cat - dog - rabbit - snake - turtle name: type: string oneOf: - $ref: "#/components/schemas/Cat" - $ref: "#/components/schemas/Dog" - $ref: "#/components/schemas/Rabbit" - $ref: "#/components/schemas/Snake" - $ref: "#/components/schemas/Turtle" ``` -------------------------------- ### OpenAPI `oneOf` Usage for TypeScript Unions Source: https://openapi-ts.dev/6.x/advanced Illustrates the TypeScript type generated from an OpenAPI schema using `oneOf` in combination with other properties. It shows the resulting complex union and intersection type, and notes the limitation in discriminating types via a `type` property. ```typescript Pet: ({ /** @enum {string} */ type?: "cat" | "dog" | "rabbit" | "snake" | "turtle"; name?: string; }) & (components["schemas"]["Cat"] | components["schemas"]["Dog"] | components["schemas"]["Rabbit"] | components["schemas"]["Snake"] | components["schemas"]["Turtle"]); ``` -------------------------------- ### OpenAPI `$defs` with Non-Object Types to TypeScript Source: https://openapi-ts.dev/6.x/advanced Shows the TypeScript output when `$defs` are incorrectly used with a non-object type in an OpenAPI schema. It demonstrates the resulting TypeScript error where the `$defs` property does not exist on the string type. ```typescript export interface components { schemas: { DefType: string; MyType: { myType?: components["schemas"]["DefType"]["$defs"]["myDefType"]; }; }; } ``` -------------------------------- ### OpenAPI `$defs` with Non-Object Types to TypeScript Source: https://openapi-ts.dev/6.x/advanced Highlights an incorrect usage of `$defs` with a non-object type in an OpenAPI schema, leading to potential issues in TypeScript generation. It shows how referencing `$defs` from a string type results in an error. ```yaml components: schemas: DefType: type: string $defs: myDefType: type: string MyType: properties: myType: $ref: "#/components/schemas/DefType/$defs/myDefType" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.