Tobias
Tobias

Reputation: 2985

Swagger/NSwag: Redefine Parameter Type

We are using swagger / nswag for documentation of a webapi project.

As BodyParameters for the ActionMethods we use classes with the suffix Command, that contain parameters for e.g. creating a Domain-Object persisted in a database.

A Command-Class could look like this:

public class CreateChildCommand {
    public Parent Parent { get; set; }
    public int Position { get; set; }
}

While Position is a simple int, Parent is a Domain-Class persisted in a database. May it look somehow like this:

public class Parent {

    public Guid Id { get; set; }
    public string Name { get; set; }
    ...
}

It can be loaded from database by its Id, so we just pass the id as parameter in the Json for the Command-Parameter like this:

{
    "Position": 3,
    "Parent": "41E71207-7F1E-4895-8BCC-14E1293A7907"
}

When deserializing the Json the parent gets loaded by its Id via a Dao. The problem now is, that swagger/nswag doesn't understand that "magic" and displays the parameters for the method like this:

{
    "Position": number,
    "Parent": {
         Id: "Guid",
         "Name": "string",
         ...
    }
}

Is there any way to tell swagger to replace the Type for parent to make it look like this:

{
    "Position": "int",
    "Parent": "Guid"
}

Upvotes: 3

Views: 4999

Answers (1)

Rico Suter
Rico Suter

Reputation: 11858

You can use the JsonSchemaAttribute attribute to override the schema type of a complex property:

public class CreateChildCommand {
    [JsonSchema(JsonObjectType.String, Format = "guid")]
    public Parent Parent { get; set; }

    public int Position { get; set; }
}

The attribute is implemented in the NJsonSchema library: https://www.nuget.org/packages/NJsonSchema/

Another option is to use a type mapper to map all Parent classes to a string, see https://github.com/RSuter/NJsonSchema/wiki/Type-Mappers

Upvotes: 6

Related Questions