سؤال

I have a REST API written using ASP.NET Core Web API. There are a few business logic based messages I want to send to the clients from the API.

I am in a dilemma on which of the following ways I can use to show the messages:

Method 1:

Assign a unique code(number) for each message, send that code to the clients and decide the message to be shown on the client based on the code received.

Method 2:

Directly send a response to the clients, along with the appropriate developer and user messages for the scenario and display the user message.

I am hesitant on using method 1 as I have multiple clients for the API and the codes should be handled at both the places and would result in duplication of messages but I have read on a stackoverflow thread that method 2 is better as it would help with stuff like localization of messages and is kind of a best practice.

Can you please advise me on which method would be the best or if there is a better way than the two mentioned above?

هل كانت مفيدة؟

المحلول

My advice: do both. :)

The API client can decide to use the messages from your API or read each error code and create his own messages. Like:

{
    "errorCode": "4005",
    "message": "Person already registered"
}

But if you need to choose one, I would choose the error code solution.

The reason: if your API client needs to show another message instead of the API message, the client will not able to have any unique identification of this API error message to map his own message. He will need to make some risk implementation, like mapping the entire API message with his client message, but this approach will break when the API decide to do any correction on the message.

I am hesitant on using method 1 as I have multiple clients for the API and the codes should be handled at both the places and would result in duplication of messages

This "duplication" is not really true, because I assume that each client has his own particularities and his way to show the best messages for his user. This "user view" problem is more a client problem, not an API problem. Your API needs to be more independent of what the clients are doing when consuming the API and concentrate on communicate well what kind of error is happening. When you have some doubt about your API responsibility, make your decision thinking that your API will be public and opened for anyone on the world to use :)

نصائح أخرى

Variation on the "do both" theme:

Return error codes from your API and provide an additional API for error code translations. This service could handle localization, and by keeping business specific messages on the server you avoid having to update the client when new messages are defined to handle new rules.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى softwareengineering.stackexchange
scroll top