Code Monkey home page Code Monkey logo

openapi-ts's Introduction

Logo

OpenAPI Typescript

✨ Turn your OpenAPI specification into a beautiful TypeScript client.

Generate TypeScript interfaces, REST clients, and JSON Schemas from OpenAPI specifications.

Live demo

Features

  • works with CLI, Node.js, or npx
  • supports OpenAPI 2.0, 3.0, and 3.1 specifications
  • supports both JSON and YAML input files
  • supports external references using json-schema-ref-parser
  • generates TypeScript interfaces, REST clients, and JSON Schemas
  • Fetch API, Axios, Angular, Node.js, and XHR clients available
  • abortable requests through cancellable promise pattern

Documentation

Please visit our website for documentation, guides, migrating, and more.

GitHub Integration (coming soon)

Automatically update your code when the APIs it depends on change. Find out more.

Migrating from OpenAPI Typescript Codegen?

Please read our migration guide.

Contributing

Want to get involved? Please refer to the contributing guide.

openapi-ts's People

Contributors

askvortcov avatar bakakaba avatar budde377 avatar dbo avatar dependabot-preview[bot] avatar dependabot[bot] avatar edwinveldhuizen avatar ferdikoomen avatar fpoppinga avatar github-actions[bot] avatar jordanshatford avatar josstn avatar jurgenbelien avatar kraenhansen avatar krokettenkoal avatar markbrockhoff avatar mb21 avatar mlankamp avatar mlaps-gafe avatar mrlubos avatar mrtnvh avatar nandorojo avatar nicolas-chaulet avatar nikopavlica avatar or-zarchi-forter avatar pitmulleringka avatar raman-savitski-exadel avatar tajnymag avatar troglotit avatar vyobukhov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

openapi-ts's Issues

Remove `indent` option

User should process output in their code formatter/linter of choice to adhere to their code style.

useDateType should convert datetime strings to date objects.

Describe the problem

useDateType marks the models as Date objects.
The service does not convert the date strings to date objects.

This is causing the model generated as (Date) to be incorrect compared to the actual data (string). This library should take care of the conversion.

Describe the proposed solution

The useDateType should convert the string in the datetime format to a JS Date object so the data types match.

Alternatives considered

No response

Importance

nice to have

Additional information

No response

Can be use an options file ?

Hi,
first time with this openapi ts generator. I have this script into my package.json :

"gen:api-create-services": "npx @nicolas-chaulet/openapi-typescript-codegen -i http://localhost:5005/openapi.json -o src/generated/client -c angular --exportSchemas true",

To make simple, Is it provided an option file ?

"gen:api-create-services": "npx @nicolas-chaulet/openapi-typescript-codegen -f myoptions.json"

Thank you

feat: automate releases and changelogs

@mrlubos would you up to adding https://github.com/changesets/changesets to the project? They are a great tool for managing changesets and releases. Provided we add a NPM token to the repositories secrets.

I think it would be good to get back to updating the changelog (I can backtrack the current releases not included in it).

I can also setup changesets in the repository and CI if you would like.

Let me know your thoughts and I can implement this (or assign it to me). Also if possible could you add a NPM_TOKEN secret for use in actions (so that the release portion will work)

falsy values not being added to the query string

Describe the bug

When performing a GET request with falsy values such as 0 or false, these values are not being appended to the query string.

This occurs due to the logic implemented in the process function located at line 9 inside https://github.com/nicolas-chaulet/openapi-typescript-codegen/blob/master/src/templates/core/functions/getQueryString.hbs. The conditional check if (value) will not include falsy values in the query string.

A Possible solution could be to check for the value type or allow to pass a custom getQueryString function

Reproduction

Do a GET request using falsy values as query parameters, you will see in the network tab that they are not being applied to the final query string.

Logs

No response

System information

Linux, Chrome

Severity

annoyance

Additional information

No response

Config option to specify file header

Describe the problem

I would to have an option to insert a custom file header into each file, this would allow me to add options to disable eslint etc.

Describe the proposed solution

In the config file have something like:

/** @type {import('@hey-api/openapi-ts').UserConfig} */
export default {
  input: 'path/to/openapi.json',
  output: 'src/client',
  header: '/* istanbul ignore file */ \n /* tslint:disable */ \n /* eslint-disable */'
}

Alternatives considered

No response

Importance

nice to have

Additional information

No response

Fix e2e tests

Describe the problem

They currently fail if anything else runs on port 3000

Describe the proposed solution

Do not fail

Alternatives considered

No response

Importance

nice to have

Additional information

No response

Command line options

Describe the bug

In the readme there are 2 options:

--no-format
--no-lint

I think they are never used or am I wrong?

OpenAPI specification

n.a.

Generated client

No response

System information

n.a.

Severity

annoyance

Additional information

No response

[Meta] Multipart requests need rework

Describe the bug
Right now, binary multipart/form-data requests almost always fail to work.

Issues:

In my testing, I've used example requests from Swagger documentation and compared the result to the official java-based typescript-axios generator. The official generator correctly inferred the requests were containing files, made the operation input be File instead of Blob and correctly serialized and performed the request.

Pass schemas to interceptors?

Explore passing generated schemas to interceptors. If they can be passed as another argument, client could look at each field type and automatically de/serialize dates as an example. Investigate how this might work with nested schemas, we need to be able to process nested fields too.

Missing types in client gen

Hellooo,
Firstly, thanks for forking and implementing ferdikoomen/openapi-typescript-codegen#2044.
I'm happy to try and chip in where I can too.

I've just switched the library out for the fork, but the code generated in the client appears to be invalid.

Types of TResult, TConfig, TApiResponse are all missing in the generated files.

They seem to exist in core/types.ts, they're just not being templated into this file.

Screenshot 2024-03-04 at 10 39 38

No types for generate

Describe the bug

I was looking to trying this fork out, but I am not able to use it programmatically at all.

This PR #82 seems to have changed the released files and types. And currently it only includes the config types, not for the actual generate-function.

There also seems to be some issues with the released files, as I cannot import this in my ts-node project with moduleResolution nodenext and esm: true. This is probably an issue with my setup though, related this now being type: module.

Reproduction

import OpenAPI from '@nicolas-chaulet/openapi-typescript-codegen'
// or
import * as OpenAPI from '@nicolas-chaulet/openapi-typescript-codegen'

Only UserConfig and defineConfig seems to be exported

Logs

No response

System information

Mac, ts-node. Node v18.12.1

Severity

annoyance

Additional information

No response

feat: enable dependabot and codeql scanning

@mrlubos It doesnt appear to be enabled here (as I am seeing issues on my fork, but not here).

Also I have sent you an email (to the one linked on your github), about this repository and making it more accessible to stay maintained. When you get a chance take a look at it.

Properly handle readOnly and writeOnly properties

Describe the solution you'd like
As described at original issue and pull request openapi-typescript-codegen does not handle readOnly and writeOnly properties of openapi schemas.

With these properties, it is easier to model properties not for modifiable models.

OpenAPI example:

type: object
properties:
  id:
    # Returned by GET, not used in POST/PUT/PATCH
    type: integer
    readOnly: true
  username:
    type: string
  password:
    # Used in POST/PUT/PATCH, not returned by GET
    type: string
    writeOnly: true

Expected example types (not necessary to be generated separately, as @tiholic suggested in his PR):

UserGetResponse: { id: number, username?: string }
UserPostRequest: { id: number, username?, password?: string }
UserPutRequest: { id: number, username?, password?: string }
UserPatchRequest: { id: number, username?, password?: string }

Support for legacy enum

Describe the problem

When upgrading from openapi-typescript-codegen the handling of enum is totally different and based on the thread #60 I understand why. But this causes so large upgrade issues in our code base.

Describe the proposed solution

It would be nice to have an --useLegacyEnum flag which would use the typescript enum construct.

Alternatives considered

No response

Importance

nice to have

Additional information

No response

Add support for import mappings

Describe the problem

Currently, it is only possible to refer to types descriptions that are already in the schema. But there are cases when you would like to refer to external generated types.

Describe the proposed solution

Add another config file openapi-ts.importMappings.mjs or something like that, where the mappings will be listed:

export default {
  SomeCustomModel: '../../path/to/SomeCustomModel',
  YetAnotherCustomModel: '../../path/to/YetAnotherCustomModel',
}

If there are a config file and types in it, then we ignore references to these types in the schema, but add imports to models.ts (exportModel.hbs) and DefaultService.ts (exportService.hbs)

As a result, the models.ts should look like this:

import SomeCustomModel from '../../path/to/SomeCustomModel',
import YetAnotherCustomModel from '../../path/to/YetAnotherCustomModel',

/**
 * Model generated from schema
 */
export type ModelGeneratedFromSchema = {
  prop: SomeCustomModel;
  anotherProp?: YetAnotherCustomModel;
};

Alternatives considered

No response

Importance

cannot use project without

Additional information

No response

Empty model.ts and schema.ts cause project to crash after generating code

Describe the bug

models.ts and schema.ts are empty which causes the following issue microsoft/TypeScript#46343,

OpenAPI specification

openapi: "3.0.0"
info:
  version: 1.0.0
  title: Guard Dog
  description: A set of endpoints used in local and development environments to run automated e2e testing

servers: []

paths:
  /auth/system.token:
    get:
      summary: "Get a \"system\" token that can perform all actions regardless of the organisation"
      responses:
        200:
          description: Success
          content:
            application/json:
              schema:
                type: object
                required:
                  - token
                properties:
                  token:
                    required:
                    type: string

  /auth/{id}/token:
    get:
      summary: "Get a token for a specific user"
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        200:
          description: Success
          content:
            application/json:
              schema:
                type: object
                required:
                  - token
                properties:
                  token:
                    required:
                    type: string

  /temporal/workflows/{id}:
    get:
      summary: "Get a workflow by ID"
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        200:
          description: Success
          content:
            application/json:
              schema:
                type: object
                required:
                  - id
                  - status

                properties:
                  id:
                    type: string

                  status:
                    type: string
                    enum:
                      - "Unspecified"
                      - "Running"
                      - "Completed"
                      - "Failed"
                      - "Canceled"
                      - "Terminated"
                      - "ContinueAsNew"
                      - "TimedOut"

Client

Fetch

Generated client

No response

System information

No response

Severity

breaking

Additional information

No response

Generating of enums in latest version (0.27.27)

Describe the bug
The generated file looks something like this:

export enum DownloadState {
	WAITING = 'WAITING',
	DOWNLOADING = 'DOWNLOADING',
	PROCESSING = 'PROCESSING',
	DONE = 'DONE',
	ERROR = 'ERROR'
}
export type TDownloadState = 'WAITING' | 'DOWNLOADING' | 'PROCESSING' | 'DONE' | 'ERROR';

The issue is that DownloadState is exported from the index file but TDownloadState is used in the generated code. Should we only have one or the other?

Do not set default parameters in client

A default parameter value means the server will use that value if nothing else is provided to it in the request. Therefore, sending the default value in request is redundant and can be removed.

Add support for changing BASE

My openapi.json schema is being generated from production.

However, for this to work in localhost/testing/staging I would need the BASE to be '':

export const OpenAPI: OpenAPIConfig = {
    BASE: '', => change this!
    CREDENTIALS: 'include',
    ENCODE_PATH: undefined,
    HEADERS: undefined,
    PASSWORD: undefined,
    RESULT: 'body',
    TOKEN: undefined,
    USERNAME: undefined,
    VERSION: 'latest',
    WITH_CREDENTIALS: false,
};

Right now I need to change app code to set this to empty string instead..

Would be awesome if this could be done out of the box.

Is not a bug but how to use the POST ?

Describe the bug

Sorry for the dumb question. I have this method generate with your code.

    public postDevice(): Observable<void> {
        return __request(OpenAPI, this.http, {
            method: 'POST',
            url: '/device',
        })
    }

How to pass an object to body ?
I haven't found any into documentation.
Thank you in advance.

Reproduction

.

Logs

No response

System information

.

Severity

other

Additional information

No response

autoformat with eslint

Describe the problem

Currently the output only gets autoformatted with prettier but if one only uses eslint it does not autoformat at all.

Describe the proposed solution

Support autoformatting with eslint if eslint is exists but not prettier.

Alternatives considered

No response

Importance

nice to have

Additional information

No response

models-only produces broken output

Describe the bug

I only export types because I use nuxt's useFetch() for the client, unfortunately restricting the output with this fork is broken.

--exportCore false is ignored, core/ is always generated and imported
--exportSchemas false is ignored, schemas.ts is always generated and imported
--exportService false is partially respected, but we get a blank services/index.ts imported from index.ts breaking the builds.

Severity

serious, but I can work around it

Additional information

@hey-api/openapi-ts 0.31.1
node v18.19.1
ubuntu 22.04.4 amd64

Multiple classes exported from different DTO files overwrite each other during generation

If i have a folder structure like this:

lib/
  modules/
    some-module/
      dto1.ts
    some-module2/
      dto2.ts

And both dto1.ts and dto2.ts export the same Dto (by name), it becomes a last-in-wins scenario during client generation as all the models get output to one folder.

I think to solve this, models need to either be inlined into the client generation (when exportModels is false) or the models themselves need to be in subfolders separating them out

Add experimental client

Add a new flag for experimental clients.

/** @type {import('@hey-api/openapi-ts').UserConfig} */
module.exports = {
  experimental: true,
  input: 'path/to/openapi.json',
  output: 'src/client',
}

This client will work towards simplification of the API. For example, instead of

DefaultsService.callToTestOrderOfParams({
  parameterStringWithNoDefault: ''
})

we will generate types like

DefaultsService.callToTestOrderOfParams({
  query: {
    parameterStringWithNoDefault: ''
  }
})

so they can be passed directly

public static callToTestOrderOfParams(data: TDataCallToTestOrderOfParams): CancelablePromise<void> {
  const { query } = data;
  return __request(OpenAPI, {
    method: 'PUT',
    url: '/api/v{api-version}/defaults',
    query: {
      parameterOptionalStringWithDefault: 'Hello World!',
      parameterOptionalStringWithEmptyDefault: '',
      parameterStringNullableWithDefault: null,
      parameterStringWithDefault: 'Hello World!',
      parameterStringWithEmptyDefault: '',
      ...query
    }
  })
}

Do not camelcase options

Describe the problem

We do not camelcase each key in requestBody, but we camelcase parent keys (e.g. path parameters). This is inconsistent and creates unnecessary complexity. In the end, we cannot avoid working with snake case values.

Describe the proposed solution

Instead of what we have today

MyService.operationFoo({
  requestBody: {
    foo_bar: ''
  },
  bazQux: ''
})

this should become

MyService.operationFoo({
  requestBody: {
    foo_bar: ''
  },
  baz_qux: ''
})

We will need a codemod to migrate existing clients

Alternatives considered

No response

Importance

cannot use project without

Additional information

No response

Duplicate parameters with --useOptions

Describe the bug
When parameters are specified in the method and endpoint, they are duplicated, causing compilation errors.

Proposal fix:
Instead of an array of parameters, use a map and raise an error if there is a type mismatch

    public deleteV2EvEdStSdBs(data: TDataDeleteV2EvEdStSdBs): CancelablePromise<void> {
        const {
            ed,
            sd,
            ed,
            sd,
        } = data;
        return this.httpRequest.request({
            method: 'DELETE',
            url: '/v2/es/{ed}/ss/{sd}/bs',
            path: {
                'ed': ed,
                'sd': sd,
                'ed': ed,
                'sd': sd,
            },
        });
    }
  /v2/es/{ed}/ss/{sd}/bs:
    delete:
      summary: ''
      operationId: deleteV2EvEdStSdBs
      description: ''
      parameters:
        - in: path
          name: ed
          description: ''
          example: 90
          required: true
          schema:
            type: integer
        - in: path
          name: sd
          description: ''
          example: 1
          required: true
          schema:
            type: integer
      responses: { }
      tags:
        - Endpoints
      security:
        - bearerAuth: [ ]
    parameters:
      - in: path
        name: ed
        description: ''
        example: 1822555
        required: true
        schema:
          type: integer
      - in: path
        name: sd
        description: ''
        example: 4
        required: true
        schema:
          type: integer

Add `models/index.ts`

Describe the problem

Hi 👋, It is useful to have models/index.ts when I want to use only the models directory (in my usage, I want to copy only the models directory to other projects).

Describe the proposed solution

import type { User } from "../../models/User";
import type { Post } from "../../models/Post";

↓ I want to do this.

import type { User, Post } from "../../models";

Alternatives considered

No response

Importance

nice to have

Additional information

Version: "@hey-api/openapi-ts": "0.27.38"

Remove custom request file support

Describe the problem

Maintaining API is hard

Describe the proposed solution

We should support all use cases for custom requests to remove the need for this feature

Alternatives considered

No response

Importance

cannot use project without

Additional information

No response

Wrong argument order inside the templates of angular core

Describe the bug

In the angular part of the core templates, the order of the arguments passed to sendRequest is wrong.

In the request template the arguments passed to the sendRequest function are :

  1. config
  2. options
  3. http
  4. url
  5. formData
  6. body
  7. headers

But in the sendRequest template the order is the following:

  1. config
  2. options
  3. http
  4. url
  5. body
  6. formData
  7. headers

This could mess this assignation

body: body ?? formData,

Reproduction

Not applicable

Logs

No response

System information

Not applicable

Severity

annoyance

Additional information

No response

How to Set a Cookie

I need to set a cookie in the header before making an API call/request. I would like to use the static methods on the generated code to make the API call, but I'm not sure how to set the request headers. I suspect that the --request parameter would need to point to a custom request file, but I am not exactly sure what should go in that file. Can someone elaborate on this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.