C
C#5mo ago
ægteemil

✅ Describing `object` response in swagger

Hey. I have an endpoint that returns an object that looks something like this.
public record Webhook(
string Id,
PayloadType Type,
object Payload
);
public record Webhook(
string Id,
PayloadType Type,
object Payload
);
where Payload can change depending on the enum value. In typescript or other languages, I'd represent this object as a union type, but since we don't have that in C#, I'd just like to describe the possibilities of this in my swagger documentation
6 Replies
Angius
Angius5mo ago
First and foremost I'd use generics here, not object With Nswag you can use [KnownType] attribute, but IIRC it only works with derived types Not with the equivalent of any With generics, as I mentioned, you should be able to use the [Produces] attribute on the controller, though
[HttpGet]
[ProducesResponseType(typeof(Webhook<int>))]
[ProducesResponseType(typeof(Webhook<Person>))]
[ProducesResponseType(typeof(Webhook<string>))]
public async IActionResult GetWebhook()
{
// ...
}
[HttpGet]
[ProducesResponseType(typeof(Webhook<int>))]
[ProducesResponseType(typeof(Webhook<Person>))]
[ProducesResponseType(typeof(Webhook<string>))]
public async IActionResult GetWebhook()
{
// ...
}
Unknown User
Unknown User5mo ago
Message Not Public
Sign In & Join Server To View
Angius
Angius5mo ago
Ooh, you're right! You could do
Result<
OkResult<Webhook<int>>,
OkResult<Webhook<Person>>,
OkResult<Webhook<string>>
>
Result<
OkResult<Webhook<int>>,
OkResult<Webhook<Person>>,
OkResult<Webhook<string>>
>
as the return type
Unknown User
Unknown User5mo ago
Message Not Public
Sign In & Join Server To View
Angius
Angius5mo ago
Probably with a type alias lol
ægteemil
ægteemilOP5mo ago
Ahhh, I'll give that a go. Thanks!
Want results from more Discord servers?
Add your server