Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swagger predefined return type values from enum

I need to be able to tell Swagger API documentation that a certain API will return a subset of certain enum.

Imagine I have an enum UserType { User_Not_Found, User_Blocked, User_Duplicated, User_Active ...and so on }.

One api/users/search might return the user FullName in case it finds a match or "User_Not_Found" in case it doesn't.

return Request.CreateResponse(
       success ? HttpStatusCode.OK : HttpStatusCode.BadRequest, 
       success ? fullName : UserType.User_Not_Found.ToString());

Question: how do I tell swagger that on this specific API the return might return either a fullname if match is found or a "User_Not_Found" if match is not found?

like image 289
SF Developer Avatar asked Nov 10 '22 13:11

SF Developer


1 Answers

What you want to do is pretty much like having a regular method return 2 different types based on its execution. This is not possible.

I think you should return the user with a HttpStatusCode.OK if the user is found, else return a custom exception wrapped in the response with HttpStatusCode 401, 403 or 404 (based on what you want). This was you can document the exceptions and that can be reflected in the Swagger UI. However this does not reflect the Enum in the swagger.json.

    try
    {
        if (isUserFound)
        {
            return Request.CreateResponse(HttpStatusCode.OK, user);
        }
        throw new UserNotFoundException("User was not found");
    }
    catch (UserNotFoundException ex)
    {
        return Request.CreateResponse(HttpStatusCode.NotFound, ex);
    }
like image 80
Raju Avatar answered Nov 14 '22 21:11

Raju