Search code examples
typescriptinterfacefrontendapi-design

Should interfaces used for describing API responses, contain all fields or only the ones the application actually needs?


Lets say I have a API endpoint that returns and object with 20 fields. Out of these 20 fields I am only interested in two.

Should my (Typescript) interface (on the FE side), describe the whole object or only the two fields I require? Are there any (meaningful) implications of either approach?

Some considerations that come to mind:

  1. (Full) The developer can see everything that is available to him without looking at the request directly.
  2. (Only 2) The developer isn't overwhelmed by the number of fields and its complexity.
  3. (Only 2) The developer knows which fields are being used in the application, just by looking at the Interface.

A sub question: Should the responsibility be on the BE side? Should the API only return things that the FE actually needs? (Lets assume things like GraphQL and other services that let the FE create queries aren't available). Would this just bring unnecessary work for the BE team, whenever the FE needs something?

I would greatly appriciate anwsers to both questions!

Thank you!


Solution

  • In general API's should only return fields that are relevant to the FE itself. If there are fields that are important to the FE, but can sometimes be undefined, they should still be returned to the FE as a null value, because even if it is null, the FE should at least know that the field is there an sometimes needed.

    If your API Object contains 20 fields, then so should your interface, you could map the API response to an interface that only has the fields that you require for your FE, but that is

    a) Error-prone because you basically have to map to properties that may or may not be there, because you cannot know what the API response looks like in the first place and

    b) it creates unnecessary code and work that the API should do for you before it returns the response.

    Imo, it is better to know that fields are there, instead of mapping the response and essentially ignoring part of the API response. Your Models and interfaces should always be in a separate file and especially in this case, be documented what they are used for (e.g. in a comment above the property).