ASP.NET Core 2.2 REST API #2 — Versioning
Up Next: Dependency Injection & Service Registration
Have you ever wondered why v*
character patterns often exist in public APIs? Today’s topic is all about Versioning.
Whenever you expose some data from your REST API, the consumers (users that talk to the API) expect the same data format over and over again. You can’t just change the data format on the same url
in the same version. There are 2 simple reasons:
- Client code will break and you can’t get everyone to update their existing code and apps
- Other developers will not want to work with your API because it is unstable with frequent breaking changes
For now, let’s make a controller that is going to return a list of Post
items. We also need a directory to put our Domain objects into (we are going to talk about domain objects later in the series).
This method is going to be converted to an endpoint and it is just going to return an Ok
response with contents (body) being a list of Post
objects, serialised in JSON format. Let’s take a moment to think about the HTTP Verb and the URL format which our resource is going to be exposed at.
- In rest
GET
([HttpGet]
) means that our endpoint is not going to change any data in the database or anywhere else. It just returns resources. - For the URL part we are going to use
api/v1/posts
. You could also change the subdomain so the url looks likeapi.domain.com/v1/posts
but for simplicity’s sake we are going to stick with the first format.
The endpoint works as expected.
The way that the response body is structured is what we are going to call a Contract. Even if we want to change the case, from id
to Id
(which is a breaking change), we would have to make a new controller under a new version directory.
We are going to establish our ApiRoutes
in a strongly typed manner (you can look at a JavaScript equivalent here).
This is a static class and everything is constant. We can just change our string constant as the HttpGet
parameter to ApiRoutes.Posts.GetAll
.
Finally, you can also create a class called Posts
under Contracts/V1/Response
, which is essentially just a wrapper around a List<Post>
. That comes in handy, as a clean-code practise and in order to have a well-maintainable request/response
pairs and swagger configuration.
Code is available on Github and the instructional videos are located on YouTube.
Keep Coding