Should I share types between a Web API service and its client ? What are the other options?

后端 未结 3 1339
南笙
南笙 2021-01-30 20:15

We are developing a Web API RESTful service to provide access to common data to all the applications of our enterprise. To help we will also publish a Client API that encapsulat

3条回答
  •  -上瘾入骨i
    2021-01-30 20:59

    I would argue that if you are not careful, the second option could end up being less RESTful than the first. REST is less about de-coupling and more about managing and focusing the coupling between client and server.

    In a restful system you know the coupling between client and server lies in the media type definitions and the link relation definitions.

    In both options, you are effectively sharing types between the client and the server. In the first option this sharing is explicit via a concrete implementation that could be managed as a nuget package and versioned independently of client and server.

    In the second option you have two implementations of the shared types. However, I'm guessing you are not planning on defining a media type that explicitly defines what the properties of those types are. Therefore you have no single source of truth, you have nothing to define what the data contract between client and server is. How do you know when you are going to make a change that will break a client? At least with a shared library you can know that the server is now using version 1.4.7 of the shared types and the client is using 1.3.9. You can use semantic versioning on the shared type library to know when you are making a breaking change that will force the client to update.

    With the second option, you have a client and a secer that will be independently versioned and it will be much harder to keep track of whether there are breaking changes between the two versions.

    Explict Media types are always the best way to capture the contracts and version the contracts between HTTP clients and servers. However, if you don't want to go there, then the shared nuget library is the best next step because you are isolating the part of the system that is shared from the client and server implementations. This is one of the key objectives of REST. The fact that you are actually sharing an implementation library of that shared contract only affects consumers live on other platforms that can't consume that library.

    I coined the term Web Pack a few years ago to describe this idea of using a shared nuget package to contain the shared coupling. I wrote a few articles here and here on the subject.

提交回复
热议问题