Nano services with ASP.NET Core or how to build a light API
This post might seem bizzare at first. In fact the idea of writing this article did not come to me on my own. The original idea came from a James Newton King tweet, this last is offering a way to write an API in the simplest possible way, efficient and without any particular framework. I found it cool and that’s why I’m making it a post today. Here is his original tweet: https://twitter.com/JamesNK/status/1276450146365001728
Creating the app
It’s quite easy, you just need to create an ASP.NET Core app with an empty template:
As promised you can see the solution is very light: a program.cs file, a Startup.cs file, settings (app and launch setting), and no dependencies except regular framework (.NET Core and ASP.NET Core):
The Startup.cs code looks like this:
Writing our first nano service
I don’t know if the term “nano service” is right but I like it, so let’s call it a nano service 🙂
Let’s create two endpoints with the MapGet extension method (MapPost, MapDelete etc.. are also available), one that serves a list of countries, another one a country from a given id, and then let’s write their implementation:
Great isn’t it ?
And that’s it ?
Yes it’s as simple as that ! But you we can go a little bit further, why not using a service (with or without using Dependency injection system) ? Let’s do it! In the next example I will use DI system, but it’s not really relevant, I just want to show you can use it, you can instantiate directly the CountryService designed below:
Now you Startup.cs looks like this :
While we are at it, we can also protect our nano service with a token for example, you can notice the extension method .RequireAuthorization() can be chained to .MapGet() method in order to apply authorization like [Authorize] attribute does it in a controller class:
Now our nano service is protected, demo:
I showed you how to build an API with dependencies on truly minimalist frameworks.
For practical use, I would say that you could use that way to expose mocks or expose an API with real data containing very tight logic or one / two endpoints, up to you! I hope this article has sown the seed in your mind just like James Newton King did :). I you find a another use case for this, please me know!