kandi background
Explore Kits

openapi-generator | OpenAPI Generator allows generation of API client | Generator Utils library

 by   OpenAPITools Java Version: v6.0.0-beta License: Apache-2.0

 by   OpenAPITools Java Version: v6.0.0-beta License: Apache-2.0

Download this library from

kandi X-RAY | openapi-generator Summary

openapi-generator is a Java library typically used in Generator, Generator Utils, Swagger applications. openapi-generator has build file available, it has a Permissive License and it has high support. However openapi-generator has 1662 bugs and it has 19 vulnerabilities. You can download it from GitHub, GitLab, Maven.
OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (both 2.0 and 3.0 are supported). Currently, the following languages/frameworks are supported:.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • openapi-generator has a highly active ecosystem.
  • It has 11886 star(s) with 4106 fork(s). There are 190 watchers for this library.
  • There were 1 major release(s) in the last 6 months.
  • There are 2814 open issues and 2391 have been closed. On average issues are closed in 173 days. There are 345 open pull requests and 0 closed requests.
  • It has a positive sentiment in the developer community.
  • The latest version of openapi-generator is v6.0.0-beta
openapi-generator Support
Best in #Generator Utils
Average in #Generator Utils
openapi-generator Support
Best in #Generator Utils
Average in #Generator Utils

quality kandi Quality

  • openapi-generator has 1662 bugs (385 blocker, 0 critical, 718 major, 559 minor) and 60081 code smells.
openapi-generator Quality
Best in #Generator Utils
Average in #Generator Utils
openapi-generator Quality
Best in #Generator Utils
Average in #Generator Utils

securitySecurity

  • openapi-generator has 1 vulnerability issues reported (0 critical, 1 high, 0 medium, 0 low).
  • openapi-generator code analysis shows 18 unresolved vulnerabilities (0 blocker, 14 critical, 4 major, 0 minor).
  • There are 143 security hotspots that need review.
openapi-generator Security
Best in #Generator Utils
Average in #Generator Utils
openapi-generator Security
Best in #Generator Utils
Average in #Generator Utils

license License

  • openapi-generator is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
openapi-generator License
Best in #Generator Utils
Average in #Generator Utils
openapi-generator License
Best in #Generator Utils
Average in #Generator Utils

buildReuse

  • openapi-generator releases are available to install and integrate.
  • Deployable package is available in Maven.
  • Build file is available. You can build the component from source.
  • Installation instructions are not available. Examples and code snippets are available.
  • openapi-generator saves you 2136146 person hours of effort in developing the same functionality from scratch.
  • It has 870656 lines of code, 87826 functions and 12714 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
openapi-generator Reuse
Best in #Generator Utils
Average in #Generator Utils
openapi-generator Reuse
Best in #Generator Utils
Average in #Generator Utils
Top functions reviewed by kandi - BETA

kandi has reviewed openapi-generator and discovered the below as its top functions. This is intended to give you an instant insight into openapi-generator implemented functionality, and help decide if they suit your requirements.

  • Flattens all the features in this set .
  • Invoke an API
  • Create a Request object .
  • Copy this parameter .
  • Parse a part .
  • Get example value .
  • Creates a new rule .
  • Test endpoint parameters for OkHttp3 .
  • Generate a string from the given options .
  • Preprocess OpenAPI .

openapi-generator Key Features

OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)

Table of contents

copy iconCopydownload iconDownload
<dependency>
    <groupId>org.openapitools</groupId>
    <artifactId>openapi-generator</artifactId>
    <version>${openapi-generator-version}</version>
</dependency>

Launcher Script

copy iconCopydownload iconDownload
mkdir -p ~/bin/openapitools
curl https://raw.githubusercontent.com/OpenAPITools/openapi-generator/master/bin/utils/openapi-generator-cli.sh > ~/bin/openapitools/openapi-generator-cli
chmod u+x ~/bin/openapitools/openapi-generator-cli
export PATH=$PATH:~/bin/openapitools/

To generate a sample client library

copy iconCopydownload iconDownload
./bin/generate-samples.sh ./bin/configs/java-okhttp-gson.yaml

Despite Open API specification ASP.NET sees every property as mandatory

copy iconCopydownload iconDownload
[DataContract]
public partial class Profile : IEquatable<Profile>
{
    [Required]
    [DataMember(Name="walletAddress", EmitDefaultValue=false)]
    public string WalletAddress { get; set; }

    [DataMember(Name="type", EmitDefaultValue=false)]
    public string Type { get; set; }

    [DataMember(Name="id", EmitDefaultValue=false)]
    public string? Id { get; set; }

    [DataMember(Name="createdAt", EmitDefaultValue=false)]
    public DateTime? CreatedAt { get; set; }

    [Required]
    [DataMember(Name="publicName", EmitDefaultValue=false)]
    public string? PublicName { get; set; }
    //other proerpties..
}

How can I use golang generics in 1.18 to simplify the code snippet?

copy iconCopydownload iconDownload
// You can edit this code!
// Click here and start typing.
package main

import (
    "fmt"
)

type GenericOpenAPIError interface {
    Model() any
}

type Failure interface {
    GetErrors() string
}

type GenericOpenAPI struct {
    model any
}

func (g *GenericOpenAPI) Model() any {
    return g.model
}

func (g *GenericOpenAPI) Error() string {
    return "goae error"
}

type A struct {
    b string
}

func (a *A) GetErrors() string {
    return a.b
}

type B struct {
    c string
}

func (b *B) GetErrors() string {
    return b.c
}

type GetErrores interface {
    A | B
}

func getErrorMessage[T GetErrores](err error) string {
    if mainError, ok1 := err.(GenericOpenAPIError); ok1 {
        var mainErrorModel = mainError.Model()
        if t, ok := mainErrorModel.(T); ok {
            if f, ok := any(&t).(Failure); ok { // must change &t to any then type assert to Failure to tell app that there is a method GetErrors()
                return f.GetErrors()
            }
        }
    }
    return err.Error()
}

func main() {
    var err any

    err = &GenericOpenAPI{A{b: "this is error a"}}

    e, ok := err.(error)
    if !ok {
        panic("not ok!")
    }

    fmt.Println(getErrorMessage[A](e))

    // change model to B
    err = &GenericOpenAPI{B{c: "this is error b"}}

    e, ok = err.(error)
    if !ok {
        panic("not ok!")
    }

    fmt.Println(getErrorMessage[B](e))
}

How to add basepath in OpenApi so that it is autogenerated with maven?

copy iconCopydownload iconDownload
@RequestMapping("${project.name.base-path:/my-path}")

Headers are not being shown in Swagger API documentation for Ktor API (Kotlin)

copy iconCopydownload iconDownload
fun Application.demoFunction() {
    apiRouting {
        tag(Tags.DEMO) {
            route("/demo") {
                post<Headers, Boolean, DemoClass>(
                    status(HttpStatusCode.OK),
                    info(
                        "Demo endpoint",
                        "This is a demo API"
                    ),
                    exampleResponse = true,
                    exampleRequest = DemoClass(name = "john doe")
                ) { header, request ->
                    respond(true)
                }
            }
        }
    }
}

@Request("Request")
data class DemoClass(
    @PathParam("Name")
    val name: String
)

data class Headers(
    @HeaderParam("Sample Header")
    val xyz: String
)

Argument of type 'Observable&lt;Pet&gt;&amp;Observable&lt;HttpResponse&lt;Pet&gt;&gt;&amp;Observable&lt;HttpEvent&lt;Pet&gt;&gt;' is not assignable to 'Observable&lt;HttpResponse&lt;Pet&gt;&gt;'

copy iconCopydownload iconDownload
/**
     * Update an existing pet
     * Update an existing pet by Id
     * @param body Update an existent pet in the store
     * @param observe set whether or not to return the data Observable as the body, response, or events. defaults to returning the body.
     * @param reportProgress flag to report request and response progress.
     */
    //public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean): Observable<Pet>;
    public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Pet>>;
    //public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<Pet>>;
    public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false ): Observable<any> 

Generate api and models in TS with openapi-generator-cli from multiple definitions from ocelote

copy iconCopydownload iconDownload
brew tap deitsch/angler
brew install angler

Is it possible to generate controller which returns void but not Void (object type) using Open API code generator in Java?

copy iconCopydownload iconDownload
private void doDataTypeAssignment(String returnType, DataTypeAssigner dataTypeAssigner) {
    final String rt = returnType;
    if (rt == null) {
        dataTypeAssigner.setReturnType("Void");
    } else if (rt.startsWith("List")) {

Authorization with apikey in headers using dio and generated client libraries by openapi-generator-dart

copy iconCopydownload iconDownload
defaultApiClient.getAuthentication<ApiKeyAuth>("apikey")!.apiKey =
        "9dhsu8d8-an9c-d40e1-a11c-5s84ddewda5";

Kotlin JSR303 Bean Validation doesn’t work from Springboot version 2.3.0.RELEASE onwards

copy iconCopydownload iconDownload
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Build swagger-ui from open-api.yml

copy iconCopydownload iconDownload
springdoc:
  api-docs:
    enabled: false
    path: /api-docs
  swagger-ui:
    disable-swagger-default-url: true
    url: /api.yml
    path: /api-docs

Community Discussions

Trending Discussions on openapi-generator
  • Despite Open API specification ASP.NET sees every property as mandatory
  • Is there a maven plugin that I can use to generate openapi spec file from JAX-RX source files
  • How can I use golang generics in 1.18 to simplify the code snippet?
  • How to add basepath in OpenApi so that it is autogenerated with maven?
  • Headers are not being shown in Swagger API documentation for Ktor API (Kotlin)
  • How to skip generation of &quot;.openapi-generator&quot; folder when using openapi-generator?
  • Argument of type 'Observable&lt;Pet&gt;&amp;Observable&lt;HttpResponse&lt;Pet&gt;&gt;&amp;Observable&lt;HttpEvent&lt;Pet&gt;&gt;' is not assignable to 'Observable&lt;HttpResponse&lt;Pet&gt;&gt;'
  • OpenAPI Swagger Code Gen C# Server Stub Throws Exception
  • Generate api and models in TS with openapi-generator-cli from multiple definitions from ocelote
  • Is it possible to generate controller which returns void but not Void (object type) using Open API code generator in Java?
Trending Discussions on openapi-generator

QUESTION

Despite Open API specification ASP.NET sees every property as mandatory

Asked 2022-Apr-01 at 03:13

I normally generate the server code directly in https://swagger.io/ online service

Going on I decided to add more automation so I decided to use the CLI tool with aspnetcore generator: https://openapi-generator.tech/docs/generators/aspnetcore

This is the important part of the PowerShell script that triggers the generator:

"openapi-generator-cli generate -g aspnetcore -i $ymlPath -o $outPath " + `
    "--additional-properties=`"packageName=$projectName,nullableReferenceTypes=true,operationResultTask=true," +
    "operationModifier=$opModifier,generateBody=$generateBody,aspnetCoreVersion=5.0`"" | iex

YML part with model schema:

Profile:
  required: [ walletAddress, publicName ]
  properties:
    walletAddress:
      type: string
      example: '0x008F7c856B71190C6E44A51a30A4ec32F68545e0'
    type:
      type: string
      example: 'itemtype'
    id:
      type: string
      example: 'pre_LfeolJ7DINWPTmQzArvT'
    createdAt:
      type: string
      format: date-time
      example: '2022-03-29T16:59:22.9033559Z'  
    publicName:
      type: string
    publicSlugUrl:
      type: string
      format: url
    emailAddress:
      type: string
      format: email
    phoneNumber:
      type: string
    location:
      type: string
    about:
      type: string

Generated C#:

namespace XxxxXxxxx.WebApi.Models
{ 
    [DataContract]
    public partial class Profile : IEquatable<Profile>
    {
        [Required]
        [DataMember(Name="walletAddress", EmitDefaultValue=false)]
        public string WalletAddress { get; set; }

        [DataMember(Name="type", EmitDefaultValue=false)]
        public string Type { get; set; }

        [DataMember(Name="id", EmitDefaultValue=false)]
        public string Id { get; set; }

        [DataMember(Name="createdAt", EmitDefaultValue=false)]
        public DateTime? CreatedAt { get; set; }

        [Required]
        [DataMember(Name="publicName", EmitDefaultValue=false)]
        public string PublicName { get; set; }

        [DataMember(Name="publicSlugUrl", EmitDefaultValue=false)]
        public string PublicSlugUrl { get; set; }

        [DataMember(Name="emailAddress", EmitDefaultValue=false)]
        public string EmailAddress { get; set; }

        [DataMember(Name="phoneNumber", EmitDefaultValue=false)]
        public string PhoneNumber { get; set; }

        [DataMember(Name="location", EmitDefaultValue=false)]
        public string Location { get; set; }


        [DataMember(Name="about", EmitDefaultValue=false)]
        public string About { get; set; }


        public override string ToString() { //...
        }

        public string ToJson()
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
        }

        public override bool Equals(object obj)
        {
            if (obj is null) return false;
            if (ReferenceEquals(this, obj)) return true;
            return obj.GetType() == GetType() && Equals((Profile)obj);
        }

        public bool Equals(Profile other)  { //...
        }

        public override int GetHashCode( { //...
        }

        #region Operators
        // ...
        #endregion Operators
    }
}

JSON verison of OpenAPI model:

"Profile" : {
  "example" : {
    "createdAt" : "2022-03-29T16:59:22.9033559Z",
    "emailAddress" : "onxy_party@gmx.de",
    "phoneNumber" : "+6563297537",
    "publicName" : "Onxy DAO",
    "about" : "about",
    "publicSlugUrl" : "https://chain.party/onxy_dao",
    "location" : "Germany",
    "id" : "pre_LfeolJ7DINWPTmQzArvT",
    "walletAddress" : "0x008F7c856B71190C6E44A51a30A4ec32F68545e0",
    "type" : "itemtype"
  },
  "properties" : {
    "walletAddress" : {
      "example" : "0x008F7c856B71190C6E44A51a30A4ec32F68545e0",
      "type" : "string"
    },
    "type" : {
      "example" : "itemtype",
      "type" : "string"
    },
    "id" : {
      "example" : "pre_LfeolJ7DINWPTmQzArvT",
      "type" : "string"
    },
    "createdAt" : {
      "example" : "2022-03-29T16:59:22.9033559Z",
      "format" : "date-time",
      "type" : "string"
    },
    "publicName" : {
      "type" : "string"
    },
    "publicSlugUrl" : {
      "format" : "url",
      "type" : "string"
    },
    "emailAddress" : {
      "format" : "email",
      "type" : "string"
    },
    "phoneNumber" : {
      "type" : "string"
    },
    "location" : {
      "type" : "string"
    },
    "about" : {
      "type" : "string"
    }
  },
  "required" : [ "publicName", "walletAddress" ]
}

I should be able to post this payload with only the two required fields, bit i get a validation error on about all other fields:

{
    "errors": {
        "id": [
            "The Id field is required."
        ],
        "about": [
            "The About field is required."
        ],
        "location": [
            "The Location field is required."
        ],
        "publicName": [
            "The PublicName field is required."
        ],
        "phoneNumber": [
            "The PhoneNumber field is required."
        ],
        "emailAddress": [
            "The EmailAddress field is required."
        ],
        "publicSlugUrl": [
            "The PublicSlugUrl field is required."
        ]
    },
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "00-42995fb014cad1fbb999645cb61e4cf9-ade43e222f9917ae-00"
}

The app is configured in this way:

using System.Reflection;
using ChainParty.WebApi.Filters;
using ChainParty.WebApi.Formatters;
using ChainParty.WebApi.OpenApi;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services
    .AddMvc(opts => opts.InputFormatters.Insert(0, new InputFormatterStream()))
        .ConfigureApplicationPartManager(apm => {
            var originals = apm.FeatureProviders.OfType<ControllerFeatureProvider>().ToList();
            foreach (var original in originals)
                apm.FeatureProviders.Remove(original);
            apm.FeatureProviders.Add(new DefaultControllerFeatureProvider());
        })
        .AddNewtonsoftJson(opts => {
            opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            opts.SerializerSettings.Converters.Add(new StringEnumConverter
            {
                NamingStrategy = new CamelCaseNamingStrategy()
            });
        });


// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services
    .AddSwaggerGen(c => {
        c.SwaggerDoc("2.0.0", new OpenApiInfo
        {
            Title = "ChainParty",
            Description = "ChainParty (ASP.NET Core 3.1)",
            TermsOfService = new Uri("https://github.com/openapitools/openapi-generator"),
            Contact = new OpenApiContact
            {
                Name = "OpenAPI-Generator Contributors",
                Url = new Uri("https://github.com/openapitools/openapi-generator"),
                Email = "chainparty@dev4side.com"
            },
            License = new OpenApiLicense
            {
                Name = "NoLicense",
                Url = new Uri("http://localhost")
            },
            Version = "2.0.0",
        });
        c.CustomSchemaIds(type => type.FriendlyId(true));
        c.IncludeXmlComments($"{AppContext.BaseDirectory}{Path.DirectorySeparatorChar}{Assembly.GetEntryAssembly().GetName().Name}.xml");

        // Include DataAnnotation attributes on Controller Action parameters as OpenAPI validation rules (e.g required, pattern, ..)
        // Use [ValidateModelState] on Actions to actually validate it in C# as well!
        c.OperationFilter<GeneratePathParamsValidationFilter>();
    });
builder.Services
        .AddSwaggerGenNewtonsoftSupport();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
    app.UseDeveloperExceptionPage();
    app.UseSwagger(c => {
        c.RouteTemplate = "openapi/{documentName}/openapi.json";
    })
    .UseSwaggerUI(c => {
        // set route prefix to openapi, e.g. http://localhost:8080/openapi/index.html
        c.RoutePrefix = "openapi";
        //TODO: Either use the SwaggerGen generated OpenAPI contract (generated from C# classes)
        c.SwaggerEndpoint("/openapi/2.0.0/openapi.json", "ChainParty");

        //TODO: Or alternatively use the original OpenAPI contract that's included in the static files
        // c.SwaggerEndpoint("/openapi-original.json", "ChainParty Original");
    });
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.UseRouting();
app.MapControllers();

app.Run();

The only customization is the controllers name resolution.

Any help really appreciated, best regards

ANSWER

Answered 2022-Apr-01 at 03:13

As this document said:

Beginning with .NET 6, new projects include the <Nullable>enable</Nullable> element in the project file. Once the feature is turned on, existing reference variable declarations become non-nullable reference types.

In .NET 6 the non-nullable property must be required, otherwise the ModelState will be invalid.

To achieve your requirement, you can remove <Nullable>enable</Nullable> from your project file.

Another way is that you can add ? to allow nullable:

[DataContract]
public partial class Profile : IEquatable<Profile>
{
    [Required]
    [DataMember(Name="walletAddress", EmitDefaultValue=false)]
    public string WalletAddress { get; set; }

    [DataMember(Name="type", EmitDefaultValue=false)]
    public string Type { get; set; }

    [DataMember(Name="id", EmitDefaultValue=false)]
    public string? Id { get; set; }

    [DataMember(Name="createdAt", EmitDefaultValue=false)]
    public DateTime? CreatedAt { get; set; }

    [Required]
    [DataMember(Name="publicName", EmitDefaultValue=false)]
    public string? PublicName { get; set; }
    //other proerpties..
}

Source https://stackoverflow.com/questions/71693465

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install openapi-generator

You can download it from GitHub, GitLab, Maven.
You can use openapi-generator like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the openapi-generator component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Consider Popular Generator Utils Libraries
Compare Generator Utils Libraries with Highest Security
Compare Generator Utils Libraries with Permissive License
Compare Generator Utils Libraries with Highest Reuse
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.