Is a REST API with CQRS Possible?

If you’re developing an HTTP API (what most would call REST) how does that fit alongside a Task-Based UI and CQRS? How can you create a REST API with CQRS? For starters, resources don’t need to map to Entities. Second, HTTP Methods don’t need to map to CRUD. Resources can be whatever you want them to be. In which case, they can be commands and queries.

YouTube

Check out my YouTube channel where I post all kinds of content that accompanies my posts including this video showing everything that is in this post.

Resources

In some of my recent videos/blogs about Task Based UIs, I’ve had people ask how CQRS can work with “REST”. The issue is what most think is REST, isn’t actually REST at all. There’s this notion that resources need to revolve around Entities. Specifically that HTTP methods map to CRUD (Create, Read, Update, Delete) around entities.

This is incorrect.

Here’s an example of a typical example revolving around Entities and CRUD. In this case, my entity is a Product in a warehouse.

Then the common pattern is to use HTTP methods mapping to CRUD. Although HTTP methods don’t fully map to CRUD, this again is the common pattern.

So for our Product Entity, our typical API would have an API following this CRUD pattern.

Resources

This misconception that resources should be entities (such as a Product) causes confusion on how CQRS can be applied. The reality is that a resource is whatever you want it to be. It can be an Entity, but it can also represent a Command or a Query.

From the Mozilla Developer Docs:

The target of an HTTP request is called a “resource”, whose nature isn’t defined further; it can be a document, a photo, or anything else. Each resource is identified by a Uniform Resource Identifier (URI) used throughout HTTP for identifying resources.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Identifying_resources_on_the_Web

An Resource can be anything. It does not need to be an entity. It can represent a command or a query.

REST API with CQRS

In order to really apply CQRS, you’re better served with a Task Based UI that will guide users to invoke commands. Command and Queries will be resources.

REST API with CQRS

Making your commands and queries resources makes them explicit. If you were to have only resources as entities, then you would have to infer which command to call for each POST/PUT/PATCH/DELETE based on the request body.

UI Composition

The next most common question is how to do UI composition. If there are multiple services that have resources that need to be called in order to get the relevant data for a UI, how is that done?

One option is to do the composition on the client. The client will call each service to get the relevant data it needs.

This means that there will be a call to each service. For the SKU, name, Description, since that’s owned by the catalog, there will be a call to that resource.

REST API with CQRS

And the same for all other data required, such as the price from Sales.

REST API with CQRS

The other option is to do the composition on the server. This is often referred to as Backend for Frontend.

REST API with CQRS

The server will call the relevant services and compose all the data into one resource that will be returned to the client with all the relevant data it needs.

Source Code

Developer-level members of my CodeOpinion YouTube channel get access to the full source for the working demo application available in a git repo. Check out the membership for more info.

Additional Related Posts

Follow @CodeOpinion on Twitter

Software Architeture & Design

Get all my latest YouTube Vidoes and Blog Posts on Software Architecture & Design

HTTP API Problem Details in ASP.NET Core

Problem Details in ASP.NET CoreIf you’ve been writing HTTP API’s, you likely have needed to return exceptions and errors back to the consuming clients.  Before you go and grow your own solution to this common problem, there is RFC 7807 Problem Details for HTTP APIs which set out solve this problem.
“problem detail” as a way to carry machine-readable details of errors in a HTTP response to avoid the need to define new error response formats for HTTP APIs.

Problem Details in ASP.NET Core

Now that you’re on board with Problem Details, how do we use or implement this in ASP.NET Core.  Thankfully, Kristian Hellang has done all the heavy lifting and released Hellang.Middleware.ProblemDetails on NuGet.

Hellang.Middleware.ProblemDetails

Once you get the NuGet package, it’s simply a matter of adding it to your Startup’s Configure(IApplicationBuilder app):
By default with no configuration, this will return a Problem Details body and application/problem+json content type for status codes returned from MVC. This means 404’s as well as status codes you return from your controller actions explicitly. Here’s an example of the response for a 404 when a route is not found.
For making explicit returns such as UnauthorizedResult:
This returns, as you might expect:

Bad Request

Most often you might be return a BadRequestObjectResult when the users sends malformed request.  In this case the solution is pretty sweet.  Simply provide BadRequest() with an object that is or derives from Microsoft.AspNetCore.Mvc.ProblemDetails

ProblemDetailsException

Another option is throw an exception.  Specifically you can throw a ProblemDetailsException that takes a ProblemDetails as a parameter.

Mapping Exceptions to ProblemDetails

Although I’m not in love with throwing a ProblemDetailsException, one of the reasons is you may not be directly inside an MVC Controller action.  If you follow my blog enough, you know I like to decouple using something like the MediatR library.  In this case you likely won’t be throwing a ProblemDetailsException. But no worries, this situation is covered by being able to map exceptions to ProblemDetailsExceptions in the configuration.

IncludeExceptionDetails

If a 500 occurs due to an unhandled exception, this is covered.  However you likely want to see the exception details when in development.  Again, no problem!

Sample

This post really revolves around the sample on the GitHub repo.  Check it out to try it out yourself. Are you using another solution for ProblemDetails in your HTTP API’s?  Let me know in the comments or on Twitter.
Follow @CodeOpinion on Twitter

Software Architeture & Design

Get all my latest YouTube Vidoes and Blog Posts on Software Architecture & Design

RESTful JSON: Adding Links to your APIs

RESTful JSONThere’s a new media type available, RESTful JSON, that was recently registered (Feb 1st 2018) with IANA.  It’s really the simplest possible media type to use in order to start adding links to your JSON APIs.  The new media type is application/vnd.restful+json 

Adding Hyperlinks

The simplicity here is that you can start using this media type with existing APIs to start adding links to your existing objects.

  1. JSON objects MAY include a url property to indicate a link to itself
  2. JSON objects MAY append _url to properties to indicate related links

Example

Here’s an existing payload of a e-commerce shopping cart.  It has one product in the cart.

Now we are going to add a couple links.  We are going to add a link to the product in our cart to the product page, and add another link to provide the URI for the checkout page.

Runtime

Links are to be used at runtime by your client.  Meaning the presents or absence of them will determine how your client behaves.  With links provided in the API, you can now traverse the payload at runtime rather than hardcode URIs.

Are you using a hypermedia content type?  I’d love to hear your comments or on Twitter.

Follow @CodeOpinion on Twitter

Software Architeture & Design

Get all my latest YouTube Vidoes and Blog Posts on Software Architecture & Design