Reputation: 716
I have a WebAPI controller with an operation returning a JSON schema. This JSON return value cannot be created by serializiation, so I designed the operation method as follow:
[HttpGet("{serviceName}/contract")]
[SwaggerResponse((int)HttpStatusCode.OK, Type = typeof(object))]
public IActionResult GetContract(string serviceName)
{
return Content("{ \"type\": \"object\" }", "application/json"); // for example ...
}
Now I like to have a or some documented return values for Swagger. But I'm unable to do that. There is the SwaggerRequestExample
attribute, but as said before, this requires a return type which in my case is not applicable.
Basically I search for a way of something like that (just dynamic):
[SwaggerResponseExample((int)HttpStatusCode.OK, "{\"anyJson\": \"Yes, I am!\"}")]
Or of course, even better like that:
[SwaggerResponseExample((int)HttpStatusCode.OK, RawJsonFabricType="TypeName", RawJsonStaticMethod="MethodName")]
Use case: The JSON schemas I need to return in operation method are stored in a database and are not created within the program code itself.
A concrete example of such a JSON schema value is:
{
"$id": "https://example.com/person.schema.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Person",
"type": "object",
"properties": {
"firstName": {
"type": "string",
"description": "The person's first name."
},
"lastName": {
"type": "string",
"description": "The person's last name."
},
"age": {
"description": "Age in years which must be equal to or greater than zero.",
"type": "integer",
"minimum": 0
}
}
}
Help will be very appreciated. Thanks!
I'm using c#.net core 6.
Upvotes: 1
Views: 4607
Reputation: 716
Afer trying arround I came to the solution:
First: Add ExampleProvider
and use generic type JsonDocument
(from System.Text.Json
):
public class ServiceDemandContractExampleProvider : IExamplesProvider<JsonDocument>
{
/// <inheritdoc/>
public JsonDocument GetExamples()
{
var jsonToShow = JsonDocument.Parse(@"{
""$id"": ""https://example.com/person.schema.json"",
""$schema"": ""https://json-schema.org/draft/2020-12/schema"",
""title"": ""Person"",
""type"": ""object"",
""properties"": {
""firstName"": {
""type"": ""string"",
""description"": ""The person's first name.""
},
""lastName"": {
""type"": ""string"",
""description"": ""The person's last name.""
},
""age"": {
""description"": ""Age in years which must be equal to or greater than zero."",
""type"": ""integer"",
""minimum"": 0
}
}
}");
return jsonToShow;
}
}
To JsonDocument.Parse
put whatever JSON (in my case loaded content from database).
Then add the follow attributes to the operation method:
[SwaggerResponse((int)HttpStatusCode.OK, Type = typeof(object))]
[SwaggerResponseExample((int)HttpStatusCode.OK, typeof(ServiceDemandContractExampleProvider))]
Upvotes: 2