g_b
g_b

Reputation: 12438

Is it a bad idea for a WebAPI to return different types depending on some condition?

I have this code which returns a different type depdending on a condition:

[HttpGet("{questionId:int}/specific")]
public async Task<IActionResult> GetSpecificByQuestionIdAsync(int questionId)
{
    IActionResult result = Ok();

    try
    {
        var question = await _questionService.GetQuestionByIdAsync(questionId);
        if (question != null)
        {
            if (question.TypeName == "TypeA")
            {
                var typeA = await _questionService.GetTypeAQuestionAsync(questionId);
                result = Ok(typeA);
            }
            else if (question.TypeName == "TypeB")
            {
                var typeB = await _questionService.GetTypeBQuestionAsync(questionId);
                result = Ok(typeB);
            }
        }
    }
    catch (Exception ex)
    {
        result = StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
    }

    return result;
}

I want to ask if this is a bad idea or is this gonna cause some problem. I tried searching but couldn't get any info regarding returning different types for REST APIs. Or is it better to make this just 2 separate calls?

Upvotes: 0

Views: 36

Answers (1)

Lutti Coelho
Lutti Coelho

Reputation: 2264

I prefer to do not return diferent types from the same URL. This will make more dificult to consume your API, as you can return diferent types of response body for the same response code (200). But if TypeA and TypeB inhiret from the same base Type and you think that would not be a problem to your consumers to handle the differences from TypeA and TypeB, maybe this should not be a problem.

I have worked with some payment APIs that have a property that has a diferent types based on the payment method used by the user. In this case, was easy to handle because the root object was always the same, just one property could be completely different, and I could known wich kind of cast I nedded to do based on the paymentType property at the root object.

If you look at some API guide lines, you probably will not see anyone saying that is a bad practice. But you will always see that are a pattern at the same url always return the same type of response. Sametimes this kind of differente results are acceptable, and sometimes are not. To answer your question you should think:
How hard will be to the consumer of this API to handle this diferent objects?

Some good api good practice references are:

One problem that I saw in your code is that you are writting the exception message on your 500 error result. This is a great risk as sometimes the exception message could show potential security risks of your application.

Upvotes: 1

Related Questions