### Full Example Server Code Source: https://openapistack.co/docs/examples Combines Express setup, openapi-backend initialization, handler registration, and middleware usage into a complete server example. ```typescript // src/server.ts import { OpenAPIBackend, Request } from 'openapi-backend'; import express from 'express'; const api = new OpenAPIBackend({ definition: './openapi.yml', }); api.init(); // handler for getPets operation in openapi.yml api.register('getPets', async (c, req: express.Request, res: express.Response) => res.status(200).json([{ id: '1', type: 'cat', name: 'Garfield' }]) ) // return 400 when request validation fails api.register('validationFail', (c, req: express.Request, res: express.Response) => res.status(400).json({ err: c.validation.errors }), ) // return 404 when route doesn't match any operation in openapi.yml api.register('notFound', (c, req: express.Request, res: express.Response) => res.status(404).json({ err: 'not found' }), ) const app = express(); // use the json middleware app.use(express.json()); // use openapi-backend to handle requests app.use((req, res) => api.handleRequest(req as Request, req, res)); // start server app.listen(9000, () => console.info('api listening at http://localhost:9000')); ``` -------------------------------- ### Quick Start with Async-Await / ES6 Source: https://openapistack.co/docs/openapi-client-axios Initialize the API client and retrieve the client instance using async-await syntax for ES6 modules. This example demonstrates creating a pet. ```javascript import OpenAPIClientAxios from "openapi-client-axios"; const api = new OpenAPIClientAxios({ definition: "https://example.com/api/openapi.json", }); api.init(); async function createPet() { const client = await api.getClient(); const res = await client.createPet(null, { name: "Garfield" }); console.log("Pet created", res.data); } ``` -------------------------------- ### Install Dependencies Source: https://openapistack.co/docs/examples/building-apis Install openapi-backend and express using npm. ```bash npm i openapi-backend express ``` -------------------------------- ### Install Dependencies Source: https://openapistack.co/docs/examples Install openapi-backend and express using npm. ```bash npm i openapi-backend express ``` -------------------------------- ### Install openapi-client-axios with npm Source: https://openapistack.co/docs/openapi-client-axios Install the library and axios using npm. ```bash npm install --save axios openapi-client-axios ``` -------------------------------- ### Basic MSW REST API Mock Setup Source: https://openapistack.co/docs/examples/testing-react-with-jest-and-openapi-mocks Set up a basic mock server using MSW to intercept and mock GET requests to '/api/pets'. This avoids the need for a real local mock backend, keeping tests fast and simple. ```javascript import { rest } from "msw"; import { setupServer } from "msw/node"; const server = setupServer( rest.get("/api/pets", (req, res, ctx) => { const pets = [{ id: 1, name: "Garfield", type: "cat" }]; return res(ctx.json({ pets })); }) ); beforeAll(() => server.listen()); afterAll(() => server.close()); ``` -------------------------------- ### Start Mock Server Source: https://openapistack.co/docs/openapicmd/mock-server Use the `mock` command followed by the path to your OpenAPI definition file to start a local mock server. The output will show the URLs for the running mock server and the OpenAPI definition. ```bash openapi mock ./openapi.yml Mock server running at http://localhost:9000 OpenAPI definition at http://localhost:9000/openapi.json ``` -------------------------------- ### Full Example: Invoking API Source: https://openapistack.co/docs/examples/calling-apis A complete example demonstrating the setup, initialization, and invocation of an API call using openapi-client-axios with TypeScript types. ```typescript // src/example.ts import { OpenAPIClientAxios } from 'openapi-client-axios'; import type { Client } from './openapi.d.ts'; const api = new OpenAPIClientAxios({ definition: 'https://example.openapistack.co/openapi.json' }); async function main() { const client = await api.init(); const petsResponse = await client.getPets(); const pets = petsResponse.data; // Pet[] inferred as type console.log('getPets response', petsResponse.status, pets); } main(); ``` -------------------------------- ### Install openapi-client-axios with yarn Source: https://openapistack.co/docs/openapi-client-axios Install the library and axios using yarn. ```bash yarn add axios openapi-client-axios ``` -------------------------------- ### Install Dependencies Source: https://openapistack.co/docs/examples/calling-apis Install the necessary openapi-client-axios and axios libraries using npm. ```bash npm i openapi-client-axios axios ``` -------------------------------- ### Install dereference-json-schema Source: https://openapistack.co/docs/utilities/dereference-json-schema Install the library using npm. This is the first step before using its functionalities. ```bash npm i dereference-json-schema ``` -------------------------------- ### Install OpenAPI Backend Source: https://openapistack.co/docs/openapi-backend/intro Install the OpenAPI Backend package using npm. ```bash npm install --save openapi-backend ``` -------------------------------- ### Start Mock API Server Source: https://openapistack.co/docs/openapicmd/intro Use `openapi mock` to start a local mock API server. You can specify the definition file, port, and various options for logging, validation, and stripping metadata. ```bash openapi mock ./openapi.yml ``` ```bash openapi mock https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v3.0/petstore.yaml ``` -------------------------------- ### Install glob-json-path Source: https://openapistack.co/docs/utilities/glob-json-path Install the glob-json-path package using npm. ```bash npm i glob-json-path ``` -------------------------------- ### Install and Run openapicmd Source: https://openapistack.co/docs/openapicmd/intro Install the openapicmd CLI globally using npm and run the help command to see available options. Alternatively, use npx to run commands without global installation. ```bash npm install -g openapicmd openapi help ``` ```bash npx openapicmd ``` -------------------------------- ### Interactive Mode Example Source: https://openapistack.co/docs/openapicmd/call Illustrates the interactive mode of the `call` command, guiding the user through operation selection, parameter input, and security scheme selection. ```APIDOC ## Interactive Mode When run without specific operation or parameters, `openapi call` enters interactive mode. ### Operation Selection ``` ? select operation ❯ GET /pet/{petId} - Find pet by ID (getPetById) POST /pet/{petId} - Updates a pet in the store with form data (updatePetWithForm) DELETE /pet/{petId} - Deletes a pet (deletePet) POST /pet/{petId}/uploadImage - uploads an image (uploadFile) GET /store/inventory - Returns pet inventories by status (getInventory) POST /store/order - Place an order for a pet (placeOrder) GET /store/order/{orderId} - Find purchase order by ID (getOrderById) (Move up and down to reveal more choices) ``` ### Parameter Input ``` ? select operation GET /pet/{petId} - Find pet by ID (getPetById) petId: 1 ``` ### Security Scheme Selection ``` ? use security scheme ◯ api_key ◯ petstore_auth ``` ### Example Result ``` GET /pet/1 { "id": 1, "name": "Dogs", "photoUrls": [ "nulla mollit veniam ea" ], "tags": [ { "id": -21297897, "name": "incididunt sed eiusmod" } ], "status": "pending" } ``` ``` -------------------------------- ### OpenAPI Specification with Examples and Schema Source: https://openapistack.co/docs/openapi-backend/mocking This OpenAPI specification demonstrates how to define responses using both an 'example' object for direct data representation and a 'schema' with an 'example' for structured data mocking. ```yaml paths: "/pets": get: operationId: getPets summary: List pets responses: 200: $ref: "#/components/responses/PetListWithExample" "/pets/{id}": get: operationId: getPetById summary: Get pet by its id responses: 200: $ref: "#/components/responses/PetResponseWithSchema" components: responses: PetListWithExample: description: List of pets content: "application/json": example: - id: 1 name: Garfield - id: 2 name: Odie PetResponseWithSchema: description: A single pet content: "application/json": schema: type: object properties: id: type: integer minimum: 1 name: type: string example: Garfield ``` -------------------------------- ### Full Example Server Code Source: https://openapistack.co/docs/examples/building-apis Complete server code integrating express and openapi-backend, including handlers and middleware. ```typescript // src/server.ts import { OpenAPIBackend, Request } from 'openapi-backend'; import express from 'express'; const api = new OpenAPIBackend({ definition: './openapi.yml', }); api.init(); // handler for getPets operation in openapi.yml api.register('getPets', async (c, req: express.Request, res: express.Response) => res.status(200).json([{ id: '1', type: 'cat', name: 'Garfield' }]) ) // return 400 when request validation fails api.register('validationFail', (c, req: express.Request, res: express.Response) => res.status(400).json({ err: c.validation.errors }), ) // return 404 when route doesn't match any operation in openapi.yml api.register('notFound', (c, req: express.Request, res: express.Response) => res.status(404).json({ err: 'not found' }), ) const app = express(); // use the json middleware app.use(express.json()); // use openapi-backend to handle requests app.use((req, res) => api.handleRequest(req as Request, req, res)); // start server app.listen(9000, () => console.info('api listening at http://localhost:9000')); ``` -------------------------------- ### Quick Start with Promises / CommonJS Source: https://openapistack.co/docs/openapi-client-axios Initialize the API client with a definition URL and make a request using promises and CommonJS syntax. Ensure the definition URL points to a valid OpenAPI JSON file. ```javascript const OpenAPIClientAxios = require("openapi-client-axios").default; const api = new OpenAPIClientAxios({ definition: "https://example.com/api/openapi.json", }); api .init() .then((client) => client.getPetById(1)) .then((res) => console.log("Here is pet id:1 from the api", res.data)); ``` -------------------------------- ### Basic Express Server Setup Source: https://openapistack.co/docs/examples Sets up a basic Express server listening on port 9000 and uses the JSON middleware. ```typescript // src/server.ts import express from 'express'; const app = express(); // use the json middleware app.use(express.json()); // start server app.listen(9000, () => console.info('api listening at http://localhost:9000')); ``` -------------------------------- ### Install openapicmd CLI Source: https://openapistack.co/docs/openapicmd Install the openapicmd CLI globally using npm or run it directly with npx. ```bash npm install -g openapicmd openapi help ``` ```bash npx openapicmd ``` -------------------------------- ### Initializing the Client Source: https://openapistack.co/docs/openapi-client-axios/usage Initialize OpenAPIClientAxios with an OpenAPI definition URL and then initialize the client to get an extended axios instance. ```APIDOC const api = new OpenAPIClientAxios({ definition: "https://example.com/api/openapi.json", }); api.init().then((client) => { // client is now an axios instance with OpenAPI capabilities }); ``` -------------------------------- ### Example Document Object Source: https://openapistack.co/docs/openapi-backend/api An example of a JavaScript object conforming to the OpenAPI Document interface, representing an OpenAPI v3.0.1 specification. ```javascript const document: Document = { openapi: "3.0.1", info: { title: "My API", version: "1.0.0", }, paths: { "/pets": { get: { operationId: "getPets", responses: { 200: { description: "ok" }, }, }, }, "/pets/{id}": { get: { operationId: "getPetById", responses: { 200: { description: "ok" }, }, }, parameters: [ { name: "id", in: "path", required: true, schema: { type: "integer", }, }, ], }, }, }; ``` -------------------------------- ### Test Mock API with `call` command Source: https://openapistack.co/docs/openapicmd/mock-server After starting the mock server, you can use the `call` command with the OpenAPI definition URL to test your mock API. ```bash npx openapi call http://localhost:9000/openapi.json ``` -------------------------------- ### Example Operation Object Source: https://openapistack.co/docs/openapi-backend/api An example of a JavaScript object conforming to the Operation interface, representing an OpenAPI Operation Object with extended properties for path and method, and dereferenced schemas. ```javascript const operation: Operation = { method: "patch", path: "/pets/{id}", operationId: "updatePetById", parameters: [ { name: "id", in: "path", required: true, schema: { type: "integer", minimum: 0, }, }, ], requestBody: { content: { "application/json": { schema: { type: "object", additionalProperties: false, properties: { name: { type: "string", }, age: { type: "integer", }, }, }, }, }, }, responses: { 200: { description: "Pet updated succesfully", }, }, }; ``` -------------------------------- ### Get Axios Instance Source: https://openapistack.co/docs/openapi-client-axios/api Retrieve the Axios client instance. If the API has not been initialized, this method will implicitly call `.init()` first. ```javascript const client = await api.getClient(); ``` -------------------------------- ### Create Request Config Object Source: https://openapistack.co/docs/openapi-client-axios/api Provides an example of a generic HTTP request configuration object, which can be created without calling an operation method. ```javascript import { RequestConfig } from 'openapi-client-axios'; const requestConfig = { method: 'put', // HTTP method url: 'http://localhost:8000/pets/1?return=id,name', // full URL including protocol, host, path and query string path: '/pets/1', // path for the operation (relative to server base URL) pathParams: { petId: 1 }, // path parameters query: { return: ['id', 'name'] }, // query parameters queryString: 'return=id,name', // query string headers: { 'content-type': 'application/json;charset=UTF-8', 'accept': 'application/json' , 'cookie': 'x-api-key=secret', }, // HTTP headers, including cookie cookies: { 'x-api-key': 'secret' }, // cookies payload: { name: 'Garfield', age: 35, }, // the request payload passed as-is } ``` -------------------------------- ### Interactive Mode: Select Security Scheme Source: https://openapistack.co/docs/openapicmd/call If your API requires authentication, interactive mode will guide you through selecting the appropriate security scheme. ```bash ? use security scheme ◯ api_key ◯ petstore_auth ``` -------------------------------- ### Example Type File for OpenAPI Client Source: https://openapistack.co/docs/openapi-client-axios/typegen Defines TypeScript types for request bodies and responses, including specific response codes like $200 and $404. ```typescript export type RequestBody = Components.RequestBodies.PetPayload; namespace Responses { export interface $200 {} export interface $404 {} } } } ``` -------------------------------- ### Launch ReDoc Source: https://openapistack.co/docs/openapicmd/generating-documentation Use the `redoc` command to quickly launch ReDoc in your browser to preview your API. ```bash openapi redoc ./openapi.yml ``` -------------------------------- ### Set up Express Server Source: https://openapistack.co/docs/examples/building-apis Initialize a basic express server and use the json middleware. ```typescript // src/server.ts import express from 'express'; const app = express(); // use the json middleware app.use(express.json()); // start server app.listen(9000, () => console.info('api listening at http://localhost:9000')); ``` -------------------------------- ### Initialize OpenAPI Definition Source: https://openapistack.co/docs/openapicmd/intro Use `openapi init` to create a new OpenAPI definition file from scratch. You can specify the title, description, version, and output format. ```bash openapi init --title 'My API' > openapi.yml ``` -------------------------------- ### Launch Swagger UI Source: https://openapistack.co/docs/openapicmd/generating-documentation Use the `swagger-ui` command to quickly launch Swagger UI in your browser to preview your API. ```bash openapi swagger-ui ./openapi.yml ``` -------------------------------- ### Example of coerceTypes Option Source: https://openapistack.co/docs/openapi-backend/api When 'coerceTypes' is enabled, query and path parameters will be of their specified types at runtime. This example shows a string 'breed' and an integer 'age' parameter. ```json { "name": "breed", "in": "query", "schema": { "type": "string" } } { "name": "age", "in": "query", "schema": { "type": "integer" } } ``` -------------------------------- ### Generate Static Documentation Bundle Source: https://openapistack.co/docs/openapicmd/generating-documentation Use the `--bundle` option with `swagger-ui` or `redoc` to create a standalone static website for your API documentation. ```bash openapi swagger-ui ./openapi.yml --bundle=outDir ``` ```bash openapi redoc ./openapi.yml --bundle=outDir ``` -------------------------------- ### Initialize API client with Async/Await (ES6) Source: https://openapistack.co/docs/openapi-client-axios/intro Initialize the API client and create a pet using async/await syntax. Requires ES6 module imports. ```javascript import OpenAPIClientAxios from "openapi-client-axios"; const api = new OpenAPIClientAxios({ definition: "https://example.com/api/openapi.json", }); api.init(); async function createPet() { const client = await api.getClient(); const res = await client.createPet(null, { name: "Garfield" }); console.log("Pet created", res.data); } ``` -------------------------------- ### Get Base URL Source: https://openapistack.co/docs/openapi-client-axios/api Retrieve the base URL for API requests. Optionally, specify an operation ID or object to get a base URL that might be overridden by the operation's or path's server configuration. ```javascript const baseURL = api.getBaseUrl(); const baseURLForOperation = api.getBaseUrl('operationId'); ``` -------------------------------- ### Get Pets Meta Source: https://openapistack.co/docs/openapi-backend/typescript Retrieves metadata related to pets. ```APIDOC ## GET /pets/meta ### Description Retrieves metadata about pets. ### Method GET ### Endpoint /pets/meta ``` -------------------------------- ### Set Up Authentication in .openapiconfig Source: https://openapistack.co/docs/openapicmd/config Configure authentication strategies for API calls using the `auth` command. This process interactively prompts for security scheme details and saves them to the `.openapiconfig` file. ```bash openapi auth https://petstore3.swagger.io/api/v3/openapi.json ? use security scheme api_key ? api_key: Set API key (api_key) secret123 Wrote auth config to /Users/viljamikuosmanen/Projects/openapi-stack/.openapiconfig. You can now use openapi call with the following auth configs: - api_key ``` -------------------------------- ### Initialize Client with Optimized Definition Source: https://openapistack.co/docs/openapi-client-axios/bundling Import the optimized OpenAPI definition (created with `--strip`) and pass it to the OpenAPIClientAxios constructor for a smaller bundle. ```javascript import definition from "./openapi-runtime.json"; const api = new OpenAPIClientAxios({ definition }); ``` -------------------------------- ### Get Pet By Id Source: https://openapistack.co/docs/openapi-backend/typescript Retrieves a pet by its unique ID. ```APIDOC ## GET /pets/{id} ### Description Retrieves a pet by its ID. ### Method GET ### Endpoint /pets/{id} ### Parameters #### Path Parameters - **id** (number) - Required - Unique identifier for pet in database ``` -------------------------------- ### Get Pets Relative Source: https://openapistack.co/docs/openapi-client-axios/typegen Retrieves pets based on a relative relationship. ```APIDOC ## GET /pets/relative ### Description Retrieves pets based on a relative relationship. ### Method GET ### Endpoint /pets/relative ### Response #### Success Response (200) - No specific fields documented. ``` -------------------------------- ### Initialize OpenAPI Backend Source: https://openapistack.co/docs/examples Initializes openapi-backend with an OpenAPI definition file. ```typescript import { OpenAPIBackend } from 'openapi-backend'; const api = new OpenAPIBackend({ definition: './openapi.yml', }); api.init(); ``` -------------------------------- ### Get Pets Metadata Source: https://openapistack.co/docs/openapi-backend/typescript Retrieves metadata related to pets, such as counts or statistics. ```APIDOC ## GET /pets/meta ### Description Retrieves metadata related to pets. ### Method GET ### Endpoint /pets/meta ### Response #### Success Response (200) - **totalPets** (number) - The total number of pets available. - **activePets** (number) - The number of currently active pets. ``` -------------------------------- ### Get Owner by Pet ID Source: https://openapistack.co/docs/openapi-backend/typescript Retrieves the owner information for a specific pet. ```APIDOC ## GET /pets/{id}/owner ### Description Retrieves the owner information for a specific pet. ### Method GET ### Endpoint /pets/{id}/owner ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the pet whose owner information is to be retrieved. ### Response #### Success Response (200) - **ownerId** (string) - The unique identifier for the owner. - **name** (string) - The name of the owner. #### Error Response (404) - **message** (string) - Indicates that the pet or its owner was not found. ``` -------------------------------- ### Create OpenAPI Client Instance Source: https://openapistack.co/docs/examples/calling-apis Import OpenAPIClientAxios and configure it with the OpenAPI definition URL to create a client instance. ```typescript import { OpenAPIClientAxios } from 'openapi-client-axios'; const api = new OpenAPIClientAxios({ definition: 'https://example.openapistack.co/openapi.json', }); ``` -------------------------------- ### Basic Authentication Source: https://openapistack.co/docs/openapicmd/call Explains how to use Basic Authentication by providing username and password directly via command-line flags. ```APIDOC ## Basic Auth For Basic Authentication, use the `--username` and `--password` flags. ### Example ```bash openapi call https://petstore3.swagger.io/api/v3/openapi.json -o getInventory --username admin --password secret123 ``` ``` -------------------------------- ### Get Pets Source: https://openapistack.co/docs/openapi-backend/typescript Retrieves a list of pets, with optional limit and offset for pagination. ```APIDOC ## GET /pets ### Description Retrieves a list of pets. ### Method GET ### Endpoint /pets ### Parameters #### Query Parameters - **limit** (number) - Optional - Number of items to return - **offset** (number) - Optional - Starting offset for returning items ``` -------------------------------- ### .mockResponseForOperation(operationId, opts?) Source: https://openapistack.co/docs/openapi-backend/api Generates a mocked response for an operation based on its schema or examples. ```APIDOC ## .mockResponseForOperation(operationId, opts?) ### Description Mocks a response for an operation based on example or response schema. Returns an object with a status code and the mocked response. ### Parameters #### Parameter: operationId - **operationId** (string) - Required - The operationId of the operation for which to mock the response #### Parameter: opts - **opts** (object) - Optional. Options for mocking. - **opts.responseStatus** (number) - Optional. The response code of the response to mock (default: 200) - **opts.mediaType** (string) - Optional. The media type of the response to mock (default: application/json) - **opts.example** (string) - Optional. The specific example to use (if operation has multiple examples) ### Example usage ```javascript api.registerHandler( "notImplemented", async (c, req: Request, res: Response) => { const { status, mock } = api.mockResponseForOperation( c.operation.operationId ); return res.status(status).json(mock); } ); ``` ``` -------------------------------- ### Initialize OpenAPI Backend Source: https://openapistack.co/docs/openapi-backend/intro Initialize OpenAPI Backend with a definition file and register handlers for operations, not found, and validation failures. ```javascript import OpenAPIBackend from "openapi-backend"; // create api with your definition file or object const api = new OpenAPIBackend({ definition: "./petstore.yml" }); // register your framework specific request handlers here api.register({ getPets: (c, req, res) => res.status(200).json({ result: "ok" }), getPetById: (c, req, res) => res.status(200).json({ result: "ok" }), notFound: (c, req, res) => res.status(404).json({ err: "not found" }), validationFail: (c, req, res) => res.status(400).json({ err: c.validation.errors }), }); // initalize the backend api.init(); ``` -------------------------------- ### Get Relative Pets Source: https://openapistack.co/docs/openapi-backend/typescript Retrieves pets that are considered 'relative' based on some internal criteria. ```APIDOC ## GET /pets/relative ### Description Retrieves pets that are considered 'relative'. ### Method GET ### Endpoint /pets/relative ### Response #### Success Response (200) - **pets** (array) - An array of relative pet objects. - **id** (string) - The unique identifier for the pet. - **name** (string) - The name of the pet. ``` -------------------------------- ### Get Pets Relative Source: https://openapistack.co/docs/openapi-backend/typescript Retrieves pets based on a relative context (details not specified). ```APIDOC ## GET /pets/relative ### Description Retrieves pets relative to a certain context. ### Method GET ### Endpoint /pets/relative ``` -------------------------------- ### Request Config Object Source: https://openapistack.co/docs/openapi-client-axios/api Structure and example of the RequestConfig object used for defining HTTP requests. ```APIDOC ## Request Config Object A `RequestConfig` object gets created as part of every operation method call. It represents a generic HTTP request to be executed. A request config object can be created without calling an operation method using `.getRequestConfigForOperation()` ```javascript import { RequestConfig } from 'openapi-client-axios'; ``` Example object ```json { "method": "put", // HTTP method "url": "http://localhost:8000/pets/1?return=id,name", // full URL including protocol, host, path and query string "path": "/pets/1", // path for the operation (relative to server base URL) "pathParams": { "petId": 1 }, // path parameters "query": { "return": ["id", "name"] }, // query parameters "queryString": "return=id,name", // query string "headers": { "content-type": "application/json;charset=UTF-8", "accept": "application/json", "cookie": "x-api-key=secret" }, // HTTP headers, including cookie "cookies": { "x-api-key": "secret" }, // cookies "payload": { "name": "Garfield", "age": 35 } // the request payload passed as-is } ``` ``` -------------------------------- ### Initialize API client with Promises (CommonJS) Source: https://openapistack.co/docs/openapi-client-axios/intro Initialize the API client with an OpenAPI definition URL and fetch a pet using promises. Requires `require` syntax. ```javascript const OpenAPIClientAxios = require("openapi-client-axios").default; const api = new OpenAPIClientAxios({ definition: "https://example.com/api/openapi.json", }); api .init() .then((client) => client.getPetById(1)) .then((res) => console.log("Here is pet id:1 from the api", res.data)); ``` -------------------------------- ### Get Pet by ID Source: https://openapistack.co/docs/openapi-backend/typescript Retrieves a specific pet's details using its unique identifier. ```APIDOC ## GET /pets/{id} ### Description Retrieves a specific pet's details by its ID. ### Method GET ### Endpoint /pets/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the pet to retrieve. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the pet. - **name** (string) - The name of the pet. - **tag** (string) - Optional - A tag associated with the pet. #### Error Response (404) - **message** (string) - Indicates that the pet with the specified ID was not found. ``` -------------------------------- ### Initialize OpenAPIClientAxios Source: https://openapistack.co/docs/openapi-client-axios/usage Initialize the client with an OpenAPI definition URL and then call init() to prepare the client for use. The init() method returns a promise that resolves with the extended axios client. ```javascript const api = new OpenAPIClientAxios({ definition: "https://example.com/api/openapi.json", }); api.init().then((client) => { client.updatePet(1, { age: 12 }); }); ``` -------------------------------- ### Get All Pets Source: https://openapistack.co/docs/openapi-backend/typescript Retrieves a list of all pets. Supports filtering and pagination via query parameters. ```APIDOC ## GET /pets ### Description Retrieves a list of all pets. ### Method GET ### Endpoint /pets ### Query Parameters - **limit** (number) - Optional - The maximum number of pets to return. - **offset** (number) - Optional - The number of pets to skip before returning results. ### Response #### Success Response (200) - **pets** (array) - An array of pet objects. - **id** (string) - The unique identifier for the pet. - **name** (string) - The name of the pet. - **tag** (string) - Optional - A tag associated with the pet. ``` -------------------------------- ### .init() Source: https://openapistack.co/docs/openapi-client-axios/api Initializes OpenAPIClientAxios by parsing the definition, dereferencing it, creating the axios instance, and setting the `initialised` flag. ```APIDOC ## .init() ### Description Initializes OpenAPIClientAxios. This method parses the input definition, dereferences it, creates the member axios instance, sets `api.initialised = true`, and returns the created axios instance. ### Returns A promise of the created member axios instance. ### Example ```javascript await api.init(); ``` ``` -------------------------------- ### Get Pet Owner Source: https://openapistack.co/docs/openapi-backend/typescript Retrieves information about a pet and its owner using both pet and owner IDs. ```APIDOC ## GET /owners/{ownerId}/pets/{petId} ### Description Retrieves a pet and its owner. ### Method GET ### Endpoint /owners/{ownerId}/pets/{petId} ### Parameters #### Path Parameters - **petId** (number) - Required - Unique identifier for pet in database - **ownerId** (number) - Required - Unique identifier for pet in database ``` -------------------------------- ### Initialize OpenAPIBackend Instance Source: https://openapistack.co/docs/openapi-backend/api Create a new instance of OpenAPIBackend with constructor options. Options include the OpenAPI definition path, validation settings, and AJV configuration. ```javascript const api = new OpenAPIBackend({ definition: "./openapi.yml", strict: true, quick: false, validate: true, ignoreTrailingSlashes: true, ajvOpts: { unknownFormats: true }, customizeAjv: () => new Ajv(), }); ``` -------------------------------- ### Get Owner By Pet Id Source: https://openapistack.co/docs/openapi-backend/typescript Retrieves the owner of a pet, identified by the pet's ID. ```APIDOC ## GET /pets/{id}/owner ### Description Retrieves the owner of a pet. ### Method GET ### Endpoint /pets/{id}/owner ### Parameters #### Path Parameters - **id** (number) - Required - Unique identifier for pet in database ``` -------------------------------- ### Get a specific operation by ID Source: https://openapistack.co/docs/openapi-backend/api Retrieve a single Operation object by its operationId using the getOperation() method. ```javascript const operation = api.router.getOperation("getPets"); console.log(`The tags for getPets are: ${operation.tags.join(", ")}`); ``` -------------------------------- ### openapi help [COMMANDS] Source: https://openapistack.co/docs/openapicmd/intro Displays help information for the OpenAPI CLI and its commands. ```APIDOC ## `openapi help [COMMANDS]` ### Description Display help for openapi. ### Usage `openapi help [COMMANDS] [-n]` ### Arguments * `COMMANDS` - Command to show help for. ### Flags * `-n, --nested-commands` - Include all nested commands in the output. ``` -------------------------------- ### Instantiate OpenAPIClientAxios with Options Source: https://openapistack.co/docs/openapi-client-axios/api Create an instance of OpenAPIClientAxios, configuring the OpenAPI definition source and default Axios settings. Ensure the OpenAPI definition is accessible. ```javascript const api = new OpenAPIClientAxios({ definition: '/openapi.json', withServer: 0, axiosConfigDefaults: { withCredentials: true, headers: { 'Cache-Control': 'no-cache', }, }, }); ``` -------------------------------- ### Get Pet Owner Source: https://openapistack.co/docs/openapi-backend/typescript Retrieves information about a specific pet and its owner using both pet and owner IDs. ```APIDOC ## GET /pets/{petId}/owner/{ownerId} ### Description Retrieves information about a specific pet and its owner. ### Method GET ### Endpoint /pets/{petId}/owner/{ownerId} ### Parameters #### Path Parameters - **petId** (string) - Required - The unique identifier of the pet. - **ownerId** (string) - Required - The unique identifier of the owner. ### Response #### Success Response (200) - **petId** (string) - The unique identifier for the pet. - **ownerId** (string) - The unique identifier for the owner. - **petName** (string) - The name of the pet. - **ownerName** (string) - The name of the owner. #### Error Response (404) - **message** (string) - Indicates that the specified pet or owner was not found. ``` -------------------------------- ### Initialize OpenAPI Client Source: https://openapistack.co/docs/examples/calling-apis Initialize the configured OpenAPI client instance. This step fetches and processes the OpenAPI definition. ```typescript const client = await api.init(); ``` -------------------------------- ### Initialize OpenAPI Backend Source: https://openapistack.co/docs/examples/building-apis Import and initialize OpenAPIBackend with your OpenAPI definition file. ```typescript import { OpenAPIBackend } from 'openapi-backend'; const api = new OpenAPIBackend({ definition: './openapi.yml', }); api.init(); ``` -------------------------------- ### Get all operations from the router Source: https://openapistack.co/docs/openapi-backend/api Retrieve a flattened array of all Operation objects defined in the OpenAPI document using getOperations(). ```javascript const operations = api.router.getOperations(); console.log(`There are ${operations.length} operations in this api`); ``` -------------------------------- ### .withServer(server) Source: https://openapistack.co/docs/openapi-client-axios/api Sets the default server base URL to be used for the client. The server can be specified by its index, description, or as a full server object to override. ```APIDOC ## .withServer(server) ### Description Set the default server base url to use for client. ### Parameters #### Parameter: server The default server to use. Either an index, description or a full server object to override with. Type: `number`, `string` or Server Object ### Example ```javascript // by index api.withServer(1); // by description property api.withServer('EU server'); // by server object (override) api.withServer({ url: 'https://example.com/api/', description: 'Eu Server' }); ``` ``` -------------------------------- ### Get Pet Metadata Source: https://openapistack.co/docs/openapi-client-axios/typegen Retrieves metadata about pets and their relations in the database. Accepts optional parameters and Axios configuration. ```APIDOC ## GET /pets/meta ### Description Returns a list of metadata about pets and their relations in the database. ### Method GET ### Endpoint /pets/meta ### Parameters #### Path Parameters - **parameters** (Parameters | null) - Optional - Path parameters, if any. #### Request Body - **data** (any) - Optional - Request body, typically not used for GET requests. #### Query Parameters - **config** (AxiosRequestConfig) - Optional - Axios request configuration. ### Response #### Success Response (200) - **OperationResponse** - The response containing pet metadata. ``` -------------------------------- ### Initialize OpenAPI Client with Runtime Spec Loading Source: https://openapistack.co/docs Use this when the OpenAPI specification needs to be resolved at runtime. The `definition` can be a URL, JSON object, or YAML string. ```javascript // openapi-client-axios — spec resolved at runtime const api = new OpenAPIClientAxios({ definition: 'https://api.example.com/openapi.json', }); const client = await api.init(); ``` -------------------------------- ### Setting Headers Source: https://openapistack.co/docs/openapicmd/call Demonstrates how to set custom headers, such as authorization tokens, using the `-H` or `--header` flag. ```APIDOC ## Setting Headers Use the `-H` or `--header` flag to include custom headers in your request. ### Example with Authorization Header ```bash openapi call https://petstore3.swagger.io/api/v3/openapi.json -o getInventory -H 'authorization: Bearer token123' ``` ``` -------------------------------- ### Get Relative Pets Metadata Source: https://openapistack.co/docs/openapi-client-axios/typegen Retrieves metadata about relative pets and their relations in the database. Accepts optional parameters and Axios configuration. ```APIDOC ## GET /pets/relative ### Description Returns a list of metadata about pets and their relations in the database. ### Method GET ### Endpoint /pets/relative ### Parameters #### Path Parameters - **parameters** (Parameters | null) - Optional - Path parameters, if any. #### Request Body - **data** (any) - Optional - Request body, typically not used for GET requests. #### Query Parameters - **config** (AxiosRequestConfig) - Optional - Axios request configuration. ### Response #### Success Response (200) - **OperationResponse** - The response containing relative pet metadata. ``` -------------------------------- ### Instantiate OpenAPIRouter Source: https://openapistack.co/docs/openapi-backend/api Create a new instance of OpenAPIRouter with options such as the OpenAPI definition, apiRoot, and whether to ignore trailing slashes. ```javascript const router = new OpenAPIRouter({ definition: api.document, apiRoot: "/", ignoreTrailingSlashes: true, }); ``` -------------------------------- ### Basic API Call Source: https://openapistack.co/docs/openapicmd/call This snippet demonstrates the basic usage of the `call` command to fetch an OpenAPI specification and initiate an API call. ```APIDOC ## Basic API Call This demonstrates how to call an API operation using the `openapi call` command. ### Command ```bash openapi call https://petstore3.swagger.io/api/v3/openapi.json ``` ### Alternative with npx ```bash npx openapicmd call https://petstore3.swagger.io/api/v3/openapi.json ``` ``` -------------------------------- ### .initSync() Source: https://openapistack.co/docs/openapi-client-axios/api Synchronously initializes OpenAPIClientAxios and creates the axios client instance. This method is only suitable when the input definition is a valid OpenAPI v3 object. ```APIDOC ## .initSync() ### Description Synchronous version of `.init()`. Initializes OpenAPIClientAxios and creates the axios client instance. Note: Only works when the input definition is a valid OpenAPI v3 object. ### Example ```javascript api.initSync(); ``` ``` -------------------------------- ### Load OpenAPI Definition to .openapiconfig Source: https://openapistack.co/docs/openapicmd/config Use the `load` command to create or update a `.openapiconfig` file with a specified OpenAPI document URL. This allows subsequent commands to use the loaded definition by default. ```bash openapi load https://petstore3.swagger.io/api/v3/openapi.json ``` -------------------------------- ### OpenAPIBackend Initialization Source: https://openapistack.co/docs/openapi-backend/api Initialize the OpenAPIBackend instance to load the OpenAPI document, build validation schemas, and register handlers. ```APIDOC ## .init() ### Description Initializes the OpenAPIBackend instance for use. This includes loading and validating the OpenAPI document, building validation schemas, and registering handlers. The `init()` method should be called after creating a new instance. Some methods will call `init()` automatically if the instance is not yet initialized. ### Returns The initialized OpenAPI backend instance. ### Example ```javascript api.init(); ``` ``` -------------------------------- ### Get Owner By Pet and Owner ID Source: https://openapistack.co/docs/openapi-client-axios/typegen Retrieves owner information using both pet and owner IDs. Accepts optional parameters and Axios configuration. ```APIDOC ## GET /pets/{petId}/owner/{ownerId} ### Description Get the owner for a pet. ### Method GET ### Endpoint /pets/{petId}/owner/{ownerId} ### Parameters #### Path Parameters - **parameters** (Parameters | null) - Optional - Path parameters, including pet ID and owner ID. #### Request Body - **data** (any) - Optional - Request body, typically not used for GET requests. #### Query Parameters - **config** (AxiosRequestConfig) - Optional - Axios request configuration. ### Response #### Success Response (200) - **OperationResponse** - The response containing the owner's information. ``` -------------------------------- ### Instantiate OpenAPIValidator Source: https://openapistack.co/docs/openapi-backend/api Creates an instance of OpenAPIValidator with options for definition, router, AJV settings, and customization. ```javascript const validator = new OpenAPIValidator({ definition: api.document, router: new OpenAPIRouter() ajvOpts: { unknownFormats: true }, lazyCompileValidators: false, customizeAjv: (originalAjv, ajvOpts, validationContext) => new Ajv(), }); ``` -------------------------------- ### Get Axios Config for Operation Source: https://openapistack.co/docs/openapi-client-axios/api Generates an axios configuration object for a specified API operation and its arguments. This is useful for custom request handling or debugging. ```javascript const request = api.getAxiosConfigForOperation('getPets', [{ petId: 1 }]) ``` -------------------------------- ### ValidationResult Object Example Source: https://openapistack.co/docs/openapi-backend/api The ValidationResult interface details the outcome of JSON schema validation. It includes a 'valid' boolean and an 'errors' array, which is null if validation passes. ```typescript import { ValidationResult } from "openapi-backend"; const validationResult: ValidationResult = { valid: false, errors: [ { keyword: "parse", dataPath: "", schemaPath: "#/requestBody", params: [], message: "Unable to parse JSON request body", }, ], }; ``` -------------------------------- ### Call API Operation with Parameters Source: https://openapistack.co/docs/openapicmd/call Skip interactive mode by providing parameters directly as command-line flags. Use `-o` for operation, `-d` for data, `-p` for path/query/header parameters, and `--security` for authentication. ```bash openapi call https://petstore3.swagger.io/api/v3/openapi.json -o updatePet -d '{"id": 1, "name":"Cats"}' -p petId=1 --security=none ``` -------------------------------- ### Mock response for an operation Source: https://openapistack.co/docs/openapi-backend/api Mocks a response for a given operationId. You can specify response status, media type, and a specific example. This is often used within a handler. ```javascript api.registerHandler( "notImplemented", async (c, req: Request, res: Response) => { const { status, mock } = api.mockResponseForOperation( c.operation.operationId ); return res.status(status).json(mock); } ); ```