DEV Community

Discussion on: Do I really need to create classes in two places?

Collapse
 
leoat12 profile image
Leonardo Teteo • Edited

This is the common practice, I don't think there is a good way to escape from it, except by using the same language in both client and API, using Javascript, most of the time. But not always this is possible, so in professional development I've seen practices to keep it updated, one of them is by using a specification, which the most used one is Swagger, which is known now as Open API specification. It happened before where I work where we developed the API and the application was made by another company, we did a specification using Swagger, it is like a contract that specifies how to communicate with the API. You can change the internals of the API the way you desire, but you CANNOT in any circumstance change the endpoints, the interfaces known by the client application. If you really need to change, the specification will have to be updated and the client will have to be notified. You can also make versions of an API like: "api.example.com/v1/endpoint" and "api.example.com/v2/endpoint" and you have to maintain all of them for the necessary time, you have to notify all the clients, if there are many you will need to maintain an old version for a long time. You can make a new endpoint with new functionality, mark the old one as deprecated in the docs/spec, but to keep backward compatibility you will need to keep old endpoints/versions most of the time.

Also, I learned that it is also good practice to decouple the database model from what is actually returned by the API, that's where DTO (Data Transfer Object) comes from. You have the database model, where you can change if needed, and the DTOs, that makes part of the contract between API and client and cannot be changed.