NSwag For ServiceStack

Viewed 32

I would like to use NSwag for generating OpenApi v3 Spec for ServiceStack(SS) based application. With SS, the contracts are defined in DTO type class and the implementations in another class making it completely decoupled.

[Route("/hello", "GET", Summary = @"Default hello service.", Notes = "Longer description for hello services")]
[Route("/hello/{Name}", "GET", Summary = @"Additional hello service", Notes="Longer description for hello services")]
public class Hello : IReturn<HelloResponse>
{
    [ApiMember(Name = "Name", Description = "Name Description",
        ParameterType = "path", DataType = "string", IsRequired = true)]
    [ApiAllowableValues("Name", typeof(string))]
    public string Name { get; set; }
}

public class HelloResponse
{
    public string Result { get; set; }
}

I need to generate the Spec file for the above code. I tried to pass the type of the class Hello to the JsonSchemaGenerator (by following the TypesToOpenApiCommand code) and it did generate the specfile but contains only the component section.

"{\"openapi\":\"3.0.0\",\"info\":{\"title\":\"Swagger specification\",\"version\":\"1.0.0\"},\"servers\":[{\"url\":\"http:///\"}],\"components\":{\"schemas\":{\"Hello\":{\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"Name\":{\"type\":\"string\",\"nullable\":true}}},\"HelloResponse\":{\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"Result\":{\"type\":\"string\",\"nullable\":true}}}}}}"

Other sections like paths, parameters were not filled in. Below is the code I used for generating the spec file,

var modelAssemblies = LoadFromAssemblies
            .Where(assembly => assembly.FullName != null && assembly.FullName.Contains(".ServiceModel"));

        var types = modelAssemblies.SelectMany(a => a.GetTypes());

        var document = CreateDocument();

        var generatorSettings = new JsonSchemaGeneratorSettings {SchemaType = SchemaType.OpenApi3};
        var generator = new JsonSchemaGenerator(generatorSettings);
        var schemaResolver = new OpenApiSchemaResolver(document, generatorSettings);

        foreach (var type in types)
        {
            generator.Generate(type, schemaResolver);
        }
        var json = document.ToJson();
        var yaml = document.ToYaml();
      
        return document;

How do I get those sections filled in? Can I get some design ideas on how to proceed forward with my requirement?

1 Answers

For an example on accessing ServiceStack's HostContext.Metadata to populate an Open API spec checkout the ServiceStack's OpenApiServices.cs.

Related