Microsoft shrunk the TypeScript

#​640 — May 25, 2023

Read on the Web

JavaScript Weekly

DeviceScript: TypeScript for Tiny Thingamabobs — DeviceScript is a new Microsoft effort to take the TypeScript experience to low-resource microcontroller-based devices. It’s compiled to a custom VM bytecode which can run in such constrained environments. (A bit like Go’s TinyGo.) It’s aimed at VS Code users but there’s a CLI option too.


The State of Node.js Performance in 2023 — Node 20 gets put through its paces against 18.16 and 16.20 with a few different benchmark suites running on an EC2 instance. It goes into a lot of depth that’s worth checking out, but if you haven’t got time, the conclusion is “Node 20 is faster.” Good.

Rafael Gonzaga

Lightning Fast JavaScript Data Grid Widget — Try a professional JS data grid component which lets you edit, sort, group and filter datasets with fantastic UX & performance. Includes a TreeGrid, API docs and lots of demos. Seamlessly integrates with React, Angular & Vue apps.

Bryntum Grid sponsor

Deno 1.34: Now deno compile Supports npm PackagesDeno isn’t Node, but it increasingly likes to wear a Node-shaped costume. This release focuses on npm and Node compatibility and Deno’s compile command (for turning projects into single binary executables) now supports npm packages too which opens up a lot of use cases.

The Deno Team


TC39’s Hemanth.HM shares some updates from TC39’s 96th meeting. Atomics.waitAsync, the /v flag for regexes, and a method to detect well formatted Unicode strings all move up to stage 4.

The Angular team shares the results of their annual developer survey. Over 12,000 Angular developers responded.


Astro 2.5

Preact 10.15 – Fast 3KB React alternative.

TypeScript 5.1 RC

Electron 24.4

MapLibre GL JS v3 – WebGL-powered vector tile maps.

???? Articles & Tutorials

Demystifying Tupper’s FormulaTupper’s self-referential formula is a formula that, when plotted, can represent itself. Confused? Luckily Eli shows us how simple the concept is and how to use JavaScript to render your own.

Eli Bendersky

An Introduction to Web Components — A practical and straightforward introduction to using the custom element API now supported in all major browsers to create a basic tabbed panel.

Mohamed Rasvi

▶  Creative Coding with p5.js in Visual Studio Codep5.js is a ‘creative coding’ library that takes a lot of inspiration from Processing. Dan does a great job at showing it off and sharing his enthusiasm for it. The main content starts at about 8-minutes in.

Daniel Shiffman and Olivia Guzzardo

Auth. Built for Devs, by Devs — Easily add login, registration, SSO, MFA, user controls and more auth features to your app in any framework.

FusionAuth sponsor

▶  Why React is Here to Stay — A rebuttal of sorts to Adam Elmore’s video from two weeks ago: ▶️ I’m Done with React.

Joscha Neske

Comparing Three Ways of Processing Arrays Non-Destructively — for-of, .reduce(), and .flatMap() go up against each other.

Dr. Axel Rauschmayer

Build Your First JavaScript ChatGPT Plugin — Plugins provide a way to extend ChatGPT’s functionality.

Mark O’Neill

How I’ve Shifted My Angular App to a Standalone Components Approach

Kamil Konopka

???? Code & Tools

Javy 1.0: A JS to WebAssembly Toolchain — Originally built at Shopify, Java takes your JS code and runs it in a WASM-embedded runtime. It’s worth scanning the example to get a feel for the process. “We’re confident that the Javy CLI is in good enough shape for general use so we’re releasing it as v1.0.0.”

Bytecode Alliance

Inkline 4.0: A Customizable Vue.js 3 UI/UX Library — A design system and numerous customizable components designed for mobile-first (but desktop friendly) and built with accessibility in mind.

Alex Grozav

Dynaboard: A Visual Web App IDE Made for Developers — Build high performance public and private web applications in a collaborative — full-stack — development environment.

Dynaboard sponsor

BlockNote: A ‘Notion-Like’ Block-Based Text Editor — Flexible and presents an extensive API so you can integrate it with whatever you want to do. You can drag and drop blocks, add real-time collaboration, add customizable ‘slash command’ menus, and more. Builds on top of ProseMirror and TipTap.


Windstatic: A Set of 170+ Components and Layouts Made with Tailwind and Alpine.js — Categorized under page sections, nav, and forms, and each category includes multiple components you can drop into projects.

Michael Andreuzza

ls-lint 2.0: A Fast File and Directory Name Linter — Written in Go but aimed at JS/front-end dev use cases, ls-lint provides a way to enforce rules for file naming and directory structures.

Lucas Löffel

Jest Puppeteer 9.0: Run Tests using Jest and Puppeteer — A Jest preset enabling end-to-end testing with Puppeteer.

Argos CI

ts-sql-query: Type-Safe SQL Query Builder — Want to build dynamic SQL queries in a type-safe way with TypeScript verifying queries? This is for you. Supports numerous SQL-based database systems and isn’t an ORM itself.

Juan Luis Paz Rojas

React Authentication, Simplified

Userfront sponsor

Hashids.js 2.3
↳ Generate YouTube-like IDs.

Tabulator 5.5
↳ Interactive table and data grid control.

gridstack.js 8.2
↳ Dashboard layout and creation library.

Cypress GitHub Action 5.8
↳ Action for running Cypress end-to-end tests.

ReacType 16.0
↳ Visual prototyping tool that exports React code.

Mongoose 7.2 – MongoDB modelling library.

Eta (η) 2.2 – Embedded JS template engine.

AVA 5.3 – Popular Node test runner.

MelonJS 15.3 – HTML5 game engine.

???? Jobs

Find JavaScript Jobs with Hired — Hired makes job hunting easy-instead of chasing recruiters, companies approach you with salary details up front. Create a free profile now.


Fullstack Engineer at — Push code, change lives. Help us become the center for good causes on the modern web with our dev tools.


????‍???? Got a job listing to share? Here’s how.

???? Node.js developer? Check out the latest issue of Node Weekly, our sibling newsletter about all things Node.js — from tutorials and screencasts to news and releases. While we include some Node related items here in JavaScript Weekly, we save most of it for there.

→ Check out Node Weekly here.

Creating full-stack web applications based on database schema for free!

Today, we’re excited to announce the free pricing plan for our CRUD tool. That means that more customers than ever before can use Flatlogic for creating a proper CRUD React/Vue/Angular web application based on the database schema.

What can you do with the free plan for the CRUD tool

You can expect the same features and functionality whether you choose our Paid access or Free option. But obviously with some limitations:

Create up to 10 applications on different technology stacks: React, Vue, Angular, Node.js, Laravel, PostgreSQL, MySQL
Create a full-fledged CRUD application (up to 3 database entities) with code written using best practices
Download or push source code to Github an unlimited number of times
Preview the code before downloading/pushing it on Github
Get updates on libraries used in your app stack
Host instantly your application demo and see the latest deployment logs

Free vs Paid access to the CRUD tool: Choose what you need

Since launching Flatlogic, we see constant growth in the creation of CRUD applications. But we understand that not all of our users need the full functionality of the CRUD tool. We also understand that in the modern world of developer tools, before investing huge resources in mastering new tools, you want to get some value here and now for free – with this motivation we introducing a free plan for creating CRUD applications.

Thus the free plan fits your needs. If you:

Want quickly prototype the CRUD app

Want to test or get familiar with new technologies before investing much time in them
See the best practice on how to organize modern CRUD apps using best practices
Prefer to use starter kits/boilerplates while starting CRUD web applications

And while our Professional plan has always offered a more enhanced way to create CRUD applications, it also required additional steps to understand your needs before getting access.

Now, you can sign up for a free account for a CRUD tool, create applications in minutes, and understand without any hassle whether Flatlogic fits your needs or not.

Create a CRUD app for free!

The post Creating full-stack web applications based on database schema for free! appeared first on Flatlogic Blog.Flatlogic Admin Templates banner

Angular Material Admin Template Update

Angular Material Admin is updated and use latest dependencies.

What products are affected by the update?

Currently, the updates were released on 2 products:

Angular Material Admin Template Full
Angular Material Admin .NET Core

What has changed?

The main update is touch the version of Angular itself, now the template are built on 13 version instead of 11.

And also we made several minor changes that make this admin dashboard template up-to-date.

Updated the Angular CLI to 13
Update Angular Material;
Updated different packages;
Updated Angular Core to 13 version.

Moving forward and Summing Up

We will be constantly updating all our Angular templates. For sure we will release this year a template based on Angular 14.

Rest of our Angular templates your can find here: Flatlogic marketplace. If you face any difficulties setting up this or that template or admin dashboard, please feel free to leave us a message on our forumTwitter or Facebook. We will respond to your inquiry as quickly as possible!

And also check our platform where you can create Angular CRUD apps literally in minutes! 

Happy developing!

The post Angular Material Admin Template Update appeared first on Flatlogic Blog.

Flatlogic Admin Templates banner

PHP MySQL Select Data Using In Page

PHP MySQL Select Data Using In Page  – The following example selects the id, firstname and lastname columns from the MyGuests table and displays it on the page:

Select Data From a MySQL Database

The SELECT statement is used to select data from one or more tables:

SELECT column_name(s) FROM table_name

or we can use the * character to select ALL columns from a table:

SELECT * FROM table_name

Example (MySQLi Object-oriented)

$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “myDB”;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die(“Connection failed: “ . $conn->connect_error);
}$sql = “SELECT id, firstname, lastname FROM MyGuests”;
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
  while($row = $result->fetch_assoc()) {
echo “id: “ . $row[“id”]. ” – Name: “ . $row[“firstname”]. ” “ . $row[“lastname”]. “<br>”;
} else {
echo “0 results”;

Code lines to explain from the example above:

First, we set up an SQL query that selects the id, firstname and lastname columns from the MyGuests table. The next line of code runs the query and puts the resulting data into a variable called $result.

The post PHP MySQL Select Data Using In Page appeared first on PHPFOREVER.

Migrating from ASP.NET Core 5.0 MVC app to 6.0

This post is about how to update an existing ASP.NET Core 5.0 MVC project to ASP.NET Core 6.0. I am sharing my experience while upgrading one of .NET 5.0 project to the .NET 6.0. First we need to upgrade TargetFramework element in the csproj file from net5.0 to net6.0. We can enable other .NET 6.0 framework features as well, like Nullable and ImplicitUsings.


Next we need to update the versions of Microsoft.AspNetCore nuget packages to the latest version of .NET 6.0.

<PackageReference Include=“Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation” Version=“6.0.0” />
<PackageReference Include=“Microsoft.AspNetCore.Authentication.JwtBearer” Version=“6.0.0” NoWarn=“NU1605” />
<PackageReference Include=“Microsoft.AspNetCore.Authentication.OpenIdConnect” Version=“6.0.0” NoWarn=“NU1605” />
<PackageReference Include=“Microsoft.EntityFrameworkCore” Version=“6.0.0” />
<PackageReference Include=“Microsoft.EntityFrameworkCore.SqlServer” Version=“6.0.0” />
<PackageReference Include=“Microsoft.Extensions.Caching.StackExchangeRedis” Version=“6.0.0” />
<PackageReference Include=“Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore” Version=“6.0.0” />

Next we can combine both Program.cs and Startup.cs. In the Program.cs remove the static void Main(), class declaration and namespace declaration etc. Here is the .NET 6.0 – Program.cs file.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
if (!app.Environment.IsDevelopment())


We can access the configuration from builder.Configuration property, like this.

builder.Services.AddDbContext<PortalDbContext>(options =>

Then we can delete the Startup.cs file. And if we enabled the Nullable attribute, we can put the ? operator after RequestId in the ErrorViewModel. Another important aspect related to Nullable feature is by default ASP.NET Core will consider every field as required if there is no nullable operator. It can be a breaking change.

I am using GitHub actions for the deployment, so I had to upgrade the Set up .NET Core step to use .NET 6.0 instead of .NET 5.0. Here is the updated GitHub Actions file.

uses: actions/[email protected]
name: Set up .NET Core
uses: actions/setup[email protected]
dotnetversion: 6.0.x
includeprerelease: true
name: Build with dotnet
run: dotnet build configuration Release

I am deploying it to Azure App Service, so I had to upgrade the .NET Version to .NET 6 (LTS) version – from the General Settings, Configuration menu. Here is the screenshot the app service configuration.

It is a simple project, so I don’t have to do much changes. Since I enabled the Nullable attribute I had to modify the code little bit. Here the official migration Guide – Migrate from ASP.NET Core 5.0 to 6.0

Happy Programming 🙂

Bring your own functions to Azure Static Web Apps

Azure Static Web Apps APIs are supported by two possible configurations: managed functions and bring your own functions. This post is about using your existing functions in Azure Static Web apps. Bring your own functions is only available in the Azure Static Web Apps Standard plan. By default Azure Static web apps support only HTTP Trigger functions. It is recommended in use cases like if we want to add some extra triggers like CosmosDB or Queue trigger or we need to manage the functions ourself. Once we enable this feature, we can’t use the default functions support in Azure Static Web App.

As the first step we need to modify the GitHub action workflow file and set the value of api_location to empty. Next you can come to the static web app configuration, and select the Functions menu, which will display a screen like this. (Bring your own function requires our Static Web App in Standard Plan, free Plan doesn’t support this feature.)

Click on the Link to a Function App link which will open a screen like this.

The function app dropdown will display all the function apps in the selected subscription. Once the function is selected, we can click on the Link button to link the function to static web app.

Now we can to access the azure function, with /api/ endpoint. There are some constraints associated to this approach. You can find more details about this approach, pros and cons and other details here – Bring your own functions to Azure Static Web Apps

Happy Programming 🙂

CARE your Web APIs with Consistent and Structured Error Responses


Designing APIs is an essential and complex process with many decisions involved that organise and hide software complexity. As we have seen in .NET Nakama (2020, August), this is accomplished by applying the principle of information hiding, which is the process of hiding the complexity of a piece of software (that is most likely to change) into modules of functionality. This will protect other parts of the software from extensive modifications. The following two important practices (among others) can be followed when designing Web APIs:

Make its users (i.e. API consumers) and us, happy. We have to understand the challenges of the API consumers (e.g. their limitations, specific needs, etc.) and try to help them by providing a user-friendly API.
Design APIs with consistent behavior (e.g. consistent use of the HTTP verbs in REST, consistent Error Handling with useful information, etc.).

APIs with consistent behavior can simplify the consumers implementation and make them happy for using our APIs. Using the HTTP error statuses (such as 4xx Client Errors and 5xx Server Errors) is a good start, but sometimes this is not sufficient to describe the different Web APIs errors. So, additional data that contains information about the problem details are needed (such as, an error-code, the data field that produced the error, etc.).

Let’s have a minute and think if we, as API designers, are really trying to understand our API consumer’s needs regarding error responses. They may be using different libraries or programming languages (they may even use JavaScript 😛). Also, let’s think about what we, as API consumers, would like from an API regarding error responses. What would make us happy?

For me, consistent and structured response-bodies on errors would make me happy because I could build and maintain usable and predictable APIs and consumers. For that reason, I started an effort to create the Consistent API Response Errors (CARE) open-source NuGet library, which handles all errors and provide consistent error responses by using an alternative “problem detail” definition with useful information (Figure 1).

This article will start by investigating the RFC7807, which defines a “problem detail” as a way to carry machine-readable details of errors in an HTTP response. Then, we will see details about the CARE code and how to use the CARE library in an ASP.NET Core API project.

Figure 1. – Consistent API Response Errors (CARE) for all error types.

RFC7807 – The Problem Details Response Format

The RFC7807 of the Internet Engineering Task Force (IETF) defines a standard format for the “problem detail” as a way to carry machine-readable details of errors in an HTTP response to avoid the need to define new error response formats for HTTP APIs.

ASP.NET Core supports by default the RFC7807 to specify errors in HTTP API responses, by using the ProblemDetails class.

The RFC7807 defines two document formats for the problem detail as JSON or XML. Depending on the selected problem detail format, the following media types are represented as a Content-Type header:

JSON: “application/problem+json” media type
XML: “application/problem+xml” media type

The main problem details object can have the following members:

type (string): A URI reference that identifies the problem type. This URI should return human-readable documentation for the problem type (e.g. using HTML).

title (string): A short, human-readable summary of the problem type.

detail (string): A longer, human-readable explanation specific to this occurrence of the problem.

instance (string): A URI reference of the specific instance that the problem has occurred.

status (number): The actual HTTP status code response as it is generated by the origin server for this occurrence of the problem.

The following code example shows a possible error by using the main RFC7807 error format, for a scenario in which the user’s account doesn’t have enough credit.

// The main RFC7807 error format.

HTTP/1.1 403 Forbidden
Content-Type: application/problem+json
Content-Language: en

“type”: “”,
“title”: “You do not have enough credit.”,
“detail”: “Your current balance is 30, but that costs 50.”,
“instance”: “/account/12345/msgs/abc”,
“status”: 403,

The main problem details object can be extended with additional members for a specific problem. So, these extended members are not pre-defined and can be any data that are related to a specific error. For example, the previous error can be extended to include the account’s “balance” and a list of URI accounts to deposit. The following code example shows an RFC7807 error with the two aforementioned extensions.

// An RFC7807 error example with two extensions for the specific problem.

HTTP/1.1 403 Forbidden
Content-Type: application/problem+json
Content-Language: en

“type”: “”,
“title”: “You do not have enough credit.”,
“detail”: “Your current balance is 30, but that costs 50.”,
“instance”: “/account/12345/msgs/abc”,
“balance”: 30,
“accounts”: [

The extensions are commonly used for specific client needs (for example, show the remaining balance). The clients (i.e. API consumers) should ignore any extensions that they don’t recognize. One of these needs is the validation errors details about the input request. The following code shows an example of such a case.

// An RFC7807 error example with extensions for validation.

HTTP/1.1 400 Bad Request
Content-Type: application/problem+json
Content-Language: en

“type”: “”,
“title”: “Your request parameters didn’t validate.”,
“invalid-params”: [
“name”: “age”,
“reason”: “must be a positive integer”
“name”: “color”,
“reason”: “must be ‘green’, ‘red’ or ‘blue'”

Consistent API Response Errors (CARE)

The RFC7807 provides a very good definition of the problem details and by using extensions it can be adapted for different API consumer’s needs. It is created to avoid the need of defining new error response formats for HTTP APIs. From my perspective, the issues of RFC7807 are that it is too generic (even for many common error cases such as validation errors) and doesn’t contain much useful information for the API consumers.

The Consistent API Response Errors (CARE), which is inspired from the RFC7807, is an effort to provide even more standardized problem details responses (for example, for validation errors) by creating an open-source NuGet library to:

Centralize the handling of the following error types (see Table 1 for details):

Validation errors,
Application exceptions and
Unhandled exceptions.

Return consistent and useful error information.
Simplify the API controllers by containing only the calls for the appropriate business-logic services (without the need of boilerplate input-validators and try-catch).

Table 1. – The type of errors that are handled by the CARE library.

Error Type

Validation Errors
It is providing details about the validation errors of the input request. The FluentValidation library can be used to define the validation rules.

Application Exceptions
Dev-defined exceptions that are thrown to provide details about application-specific or business logic issues.

Unhandled Exceptions
Exceptions are thrown when a non-recoverable error has occurred. These are common exceptions that are thrown by the .NET Common Language Runtime.

The aforementioned error types are handled by CARE providing the following two problem details response formats, which we will examine in the following sections.

General Response Error Format.
Validation Response Errors Format.

General Response Error Format

The CARE library provides the ApiBaseException class to handle the Application API exceptions, which can be used to map an HTTP status code per application exception. The HTTP status code of the Unhandled exceptions is set by default to 500 (Internal Server Error). The following table presents the fields of the error response format for the Application and Unhandled exceptions when using the CARE library.


The HTTP status code. The StatusCode and StatusMessage fields would come in handy when someone is testing the API via browser.

The HTTP status message.

A Unique Id that can be used to trace the error in your logging system for additional information (e.g. to see the Stack-Trace).

A short human-readable string that describes the error.

The following example presents the general error format for application and unhandled exceptions:

HTTP/1.1 503 Service Unavailable
Content-Type: application/problem+json

“statusCode”: 503,
“statusMessage”: “Service Unavailable”,
“errorMessage”: “No modifications were performed to the entity”,
“traceId”: “126a2854-9b27-4284-9498-3210091df834”,

Validation Response Errors Format

In an API, we would like to perform validations in the request parameters. In a multiple validation errors scenario, there is the possibility that the consumer should get more than one validation errors. The following table presents the fields of the error response format for the validations errors when using the CARE library.


The HTTP status code. The StatusCode and StatusMessage fields would come in handy when someone is testing the API via browser.

The HTTP status message.

A Unique Id that can be used to trace the error in your logging system for more information (e.g. to see the StackTrace).

An array containing multiple validation errors

A unique error code describing the specific error case. Using a numeric error code is the most common approach. Personally, I suggest the use of string-based error codes as they are easier to read and re-use.

The name of the field which has this error (as was in the incoming request).

Contains the attempted original value from the request. This is very useful in cases where an array of the same resources is accepted. The attempted-original value in the response helps the consumer to track which resource in the request had the error.

A short human-readable string that describes the error.

A URL to a page that describes this particular error in more detail.

In the following example, we can see how multiple errors (for the email and password fields) are represented.

HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8

“statusCode”: 400,
“statusMessage”: “Bad Request”,
“traceId”: “107f18b1-6585-4f08-8359-df12971e33ad”,
“errors”: [
“code”: “bad_format”,
“field”: “email”,
“attemptedValue”: “”,
“message”: “{email} is not in correct format”,
“helpURL”: “”
“code”: “not_empty”,
“field”: “password”,
“attemptedValue”: “”,
“message”: “‘password’ must not be empty.”,
“helpURL”: “”

The Source Code

The source code of the CARE library can be found on GitHub. Let’s have a quick look at the projects and the main code files (Figure 2).

ConsistentApiResponseErrors.Errors: A core library that defines the exception and response classes. This separate light library is created to be used in application layers where we only need to define and throw exceptions.

/Exceptions/: The exception classes that we could use either as base class or be thrown.

ApiBaseException.cs: A base class that can be used to create Application related API exceptions and map them with HTTP status codes and messages.

ValidationException.cs: A class that can be used to throw custom validation exceptions.

/ConsistentErrors/: The consistent response error format classes.

ExceptionError.cs: The response error format class for the Application and Unhandled Exceptions.

ValidationError.cs: The response error format class for the validation exceptions.

ConsistentApiResponseErrors: The main library contains the code for the implemented middleware and filter.

/Middlewares/ExceptionHandlerMiddleware.cs: The middleware is used to catch all exceptions and return consistent responses.

/Filters/ValidateModelStateAttribute.cs: A filter that can be used to validate the request input parameters of the controllers. In this way, there is no need to write boilerplate code anymore. Forget about the if (!context.ModelState.IsValid) { … }. In addition, the implemented filter handles the implemented FluentValidators.

Figure 2. – The files of the CARE projects.

CARE NuGet package

The CARE project is available as a NuGet package. In this section, we will see how we could use the NuGet package in a Web API project. For more examples, you can check the sample projects on GitHub.

Use CARE for Unhandled Exceptions

To let the CARE library handle all unhandled exception, we will have to use the ExceptionHandlerMiddleware in the Configure method (Startup.cs).

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
if (env.IsDevelopment())


// CARE for all Unhandled exceptions




app.UseEndpoints(endpoints =>

Use CARE for Application Exceptions

The CARE library can handle our Application Exceptions. For that purpose, we will need to change our existing exception classes to implement the ApiBaseException, which requires the definition of the following properties:

HTTP Status Code
HTTP Status Message
Error Message

For example, if we would like to throw an exception when an entity is not found, then we would start by implementing the ApiBaseException class for the specific exception (EntityNotFoundException) and define the aforementioned properties, appropriately, as we can see in the following code example.

using System;
using ConsistentApiResponseErrors.Exceptions;

namespace ExampleProject.Core.Application.Exceptions
public class EntityNotFoundException : ApiBaseException
private const int _httpStatusCode = 404;
private const string _httpStatusMessage = “Not Found”;
private const string _DefaultErrorMessage = “Entity not found”;

public EntityNotFoundException() :
base(_httpStatusCode, _httpStatusMessage, _DefaultErrorMessage)

public EntityNotFoundException(string message)
: base(_httpStatusCode, _httpStatusMessage, message)

public EntityNotFoundException(string message, Exception innerException)
: base(_httpStatusCode, _httpStatusMessage, message, innerException)

Use CARE for Validation Errors

The validation errors provide useful information to the end-user to adapt the provided input values. As we can understand, an API needs to provide the necessary error information to the API consumer in a consistent format. For example, this will provide the UI related consumer with the ability to handle all input errors and inform the user by implementing and using a common code.

In the Web API controllers, we would need to validate the input values before continuing the execution flow. When building an API, we may need to create multiple request DTOs (Data Transfer Objects) for different requests, which may share some common properties (e.g. a price value, a more complex object, etc.). The main issues here are the following:

The boilerplate code regarding the validation of the input values that is needed in each API Controller action. Sometimes, we may forget to call the input validation code.
Several validation implementations of the same input properties are sometimes created, which is not efficient to maintain.

The CARE library provides a filter to get rid of the boilerplate code regarding the validation of the input parameters. The main idea is to have clean controllers, containing only the code about the intended actions.

Re-usable input validation implementations can be performed by using the FluentValidation library. FluentValidation is a .NET library for building strongly-typed validation rules. The CARE library is compatible with the FluentValidation library to automatically perform the appropriate validations.

In this section, we will see how to configure our API to let the CARE library handle the input validations and return consistent and useful errors.

Step 1: Create Fluent-Validators for All Request DTOs

Let’s assume that we have the following request DTO (WeatherForecastRequest) with three properties: Date, Temperature in Celsius and a Summary. We can create a FluentValidator (e.g. WeatherForecastRequestValidator) in which we will add validators for the properties of the WeatherForecastRequest DTO class. For more information about fluent validator creation, you can visit the project’s website.

public class WeatherForecastRequest
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public string Summary { get; set; }

As we can see in the WeatherForecastRequestValidator class, we have defined the needed validators for our properties, the error codes, the error messages, etc. The limits of the temperature and summary length are hard-coded in this implementation. This can be improved by reading them from a configuration, a database, etc. In addition, FluentValidator supports complex properties, so that validators can be re-used in different classes.

public class WeatherForecastRequestValidator : AbstractValidator<WeatherForecastRequest>
public WeatherForecastRequestValidator()
RuleFor(x => x.TemperatureC)
.WithMessage(“The {TemperatureC} does not contain value”)
.WithMessage(“{TemperatureC} should have a lower value of -20”)
.WithMessage(“{TemperatureC} should have a greater value of 55”);

RuleFor(x => x.Summary)
.WithMessage(“{message} should have a value with maximum length of 1000”);

Step 2: Setup Using Statements

In your Startup class, add the following using statements:

using ConsistentApiResponseErrors.Filters;
using FluentValidation.AspNetCore;

Step 3: Configure the MVC Service

In your ConfigureServices class, register all validators from the assembly, by replacing the WeatherForecastRequestValidator with one of yours. In addition, suppress the .NET default validation filters to let the CARE library handle them.

public void ConfigureServices(IServiceCollection services)
// Register all validators within a particular assembly:

services.AddControllers(options =>
// Use CARE model validator to reduce code duplication

.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<WeatherForecastRequestValidator>());

// Configure the default API behavior by setting up the MVC application to suppress

// validation filters in order to be handled by the `ConsistentApiResponseErrors.Filters.ValidateModelStateAttribute`

services.Configure<ApiBehaviorOptions>(options =>
options.SuppressModelStateInvalidFilter = true;


Consistent and structured response bodies on errors are crucial when building maintainable, usable and predictable APIs. When building an API, it’s important to understand the challenges of the API consumers and try to help them with consistent API behavior.

The RFC7807 of the Internet Engineering Task Force (IETF) defines a standard format for the “problem detail” as a way to carry machine-readable details of errors in an HTTP response to avoid the need to define new error response formats for HTTP APIs. From my perspective, the issues of RFC7807 are that it is too generic (even for many common error cases such as validation errors) and doesn’t contain much useful information for the API consumers.

The Consistent API Response Errors (CARE) is an open-source NuGet library, which centralizes the error handling (of validation errors, application exceptions and unhandled exceptions), returns consistent and useful error information and, simplifies our API controllers. In this article, we have seen the CARE library’s logic, the response error formats and instructions to use the related NuGet library.

As future work, I am thinking to adapt the proposed format as extensions in the RFC7807. In this way, we will use the RFC7807 and still benefit from the advantages of the CARE project.

So, if you care about your API consumers, you want maintainable, usable, clean and predictable APIs, use the CARE library …and don’t forget that it is open-source. So, any help, suggestions, a GitHub Star, etc., are welcome.

REST Web API in Practice: Improving towards Perfection


Designing REST Web APIs in practice has many challenges. Usually, various questions are born for different parts of the project. Our decisions can determine, among others, the usability, extensibility, and performance of our APIs.

In our previous articles, we saw how the REST architectural style guides us to create Web APIs by defining six constraints (principles) and some key points that we can consider when designing APIs (.NET Nakama, 2021 September 4). Furthermore, we saw some practical suggestions for adopting consistent naming conventions in our URLs (API endpoints) and how to perform filtering, sorting, and pagination (.NET Nakama, 2021 October 4).

This article examines several topics that developers usually deal with when designing REST Web APIs. The topics include HTTP status codes, Media Types, HATEOAS, and Caching.

The catchy title about perfection is an excuse to remind us that there is no perfection in software development. There will always be bugs and space for improvement as the software and business requirements evolve. So, we can continuously improve our knowledge and code. However, our choices can take our Web APIs to the next level, but it requires always keeping in mind the following rules:

Understand the needs of the API users.
Do not follow the API best practices blindly.
Examine and document each decision.
Design APIs with consistent behavior.

HTTP Status Codes

The HTTP protocol defines a standard list of HTTP status codes that a server can respond to the client. The status codes indicate whether the client requests have been successfully received and processed by the server, an error has occurred, or some other action is needed. The HTTP status codes are grouped in the following five classes depending on the:

1xx (i.e., 100-199), Informational Response.

2xx (i.e., 200-299), Successful: The request was successfully received, understood, and accepted.

3xx (i.e., 300-399), Redirection: Further action is required to complete the request.

4xx (i.e., 400-499), Client Error: The client request contains a wrong syntax or cannot be fulfilled (i.e., the resource cannot be found).

5xx (i.e., 500-599), Server Error: The server failed to complete an apparently valid request (e.g., due to an internal error, timeout error, etc.).

Tip: The System.Net namespace contains the HttpStatusCode Enum, which includes the values of status codes defined for HTTP.

Successful HTTP Status Codes

Any Web API needs to return consistent and meaningful HTTP status codes based on their standard definition. So, for example, we shouldn’t produce a 200 OK response when returning an error. In the following table, we can see the most appropriate (for most cases) used Success HTTP status codes per HTTP method.

HTTP Method
Success HTTP Status Codes for Synchronous Operations
Success HTTP Status Codes for Asynchronous Operations


200 OK or 206 Partial Content when the contentare too big to be delivered in one response


201 Created or 200 OK when we are not creating aresource.
202 Accepted

200 OK
202 Accepted

200 OK
202 Accepted


204 No Content, meaning that we are not returning a response body (as the resource has been deleted).
202 Accepted

We are returning a 202 Accepted status code for the asynchronous operations to inform the client that the requests have been received but not yet completed. In such case, we are also returning a Location header with the URI, which the client should periodically call (using a GET method) to “ask” the server about the status of his original request (short polling). For more information about asynchronous operations, you can read the (Price E., et al., 2018).

Error HTTP Status Codes

Design APIs with consistent error handling and helpful information can eliminate confusion from the API clients when errors occur. I believe that we all had faced errors in APIs, which was almost impossible to understand the actual issue or the information was misleading. For that reason, we should use the Error HTTP Status Codes (4xx and 5xx) appropriately. In the following table, we can see some commonly used error status codes and how we should use them.

Error HTTP Status Code

400 Bad Request
The client’s request is not valid based on the server’s input validations.

401 Unauthorized
The user’s credentials are not valid (not authenticated), or the user did not provide credentials.

403 Forbidden
The user is authenticated (logged id) but doesn’t have the necessary permissions for this resource.

404 Not Found
The requested resource is not found on the server.

405 Method Not Allowed
An HTTP method is being requested that isn’t allowed for the authenticated user. For example, when a POST or PUT method is used on a read-only resource.

410 Gone
The requested resource is no longer available and will not be available again. This status code can be used for deprecated API calls (e.g., old API versions).

500 Internal Server Error
An unhandled exception occurs on the server, and a generic error message is returned.

502 Bad Gateway
The server acted as a gateway or proxy to another server from which it received an invalid response.

503 Service Unavailable
The server cannot handle the request (e.g., overloaded, down for maintenance, system failure, etc.).

504 Gateway Timeout
The server acted as a gateway or proxy to another server from which it didn’t receive a response in a specific timeframe.

When implementing .NET Core applications, you could use the open-source Consistent API Response Errors (CARE) NuGet library to centralize the error handling (validation errors, application exceptions, and unhandled exceptions) and return consistent and valuable error information.

Returning HTTP Status Code from ASP.NET Core Methods

ASP.NET Core supports methods to initialize responses for the most common status codes at the ControllerBase class (of the Microsoft.AspNetCore.Mvc namespace), such as the following.

Initialize Response to Return
Produced HTTP Status Code

200 OK

Created(Uri, Object)
201 Created

CreatedAtAction(String, Object, Object)
201 Created

204 No Content

400 Bad Request

401 Unauthorized

403 Forbidden

404 Not Found

Based on the provided Status Code.

StatusCode(Int32, Object)
Based on the provided Status Code with the objectresult.

Media Types, Accepts, and Content-Type Headers

In REST Web API, we transfer resources from the client to the server and vice versa. A resource is any information that can be named, an entity (e.g., person, ticket, product, etc.), document, file, etc. We can represent a resource in different formats, such as JSON (JavaScript Object Notation), XML (Extensible Markup Language), CSV (comma-separated values), etc. In the following example, we can see a C# class and its representations in JSON and XML.

public class ProductDto
public int ProductId { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
public List<string> Sizes { get; set; }


“productId”: 2,
“title”: “.NET T-Shirt”,
“price”: 10,
“sizes”: [

<Title>.NET T-Shirt</Title>

As we can understand, we should inform the server and the client about the format of the transferred data to transform it accordingly to their native object(s) (parsing).

In the HTTP protocol, formats are specified through media types (also known as a Multipurpose Internet Mail Extensions or MIME type). A media type is a standard (RFC 6838) that indicates the nature and format of a document, file, or bytes. The following table shows the most common formats that are used for Web APIs and their media type.

Media Type



The clients include the Accept HTTP header in their requests to determine the media type(s) that they can support. The Content-Type header is used in the client requests or server responses to define the format of the transferred data. When the accepted or requested media types are not supported, the server responds with an appropriate HTTP status code (as shown in the following table) (Price E., et al., 2018).

HTTP Header
Server HTTP Status Error Code

Determine the media type(s) that the client supports.
406 (Not Acceptable)

The format of the transferred data (in the request body).
application/json; charset=utf-8
415 (Unsupported Media Type).

In .NET Core Web APIs, we specify which media types are supported in each controller using the Consumes and Produces attributes, as shown in the following example.

public class SimpleController : ControllerBase
// The code of the controller


If you would like to support multiple response formats based on the client requests (e.g., from the URL), you can read the Andrew Lock (2017, August 01) article.


One of the REST architectural style constraints to provide a uniform interface between components is Hypermedia as the Engine of Application State (HATEOAS). Based on the HATEOAS constraint, the server should provide information for all available actions of each resource.

For example, when retrieving data of a bank account (e.g., balance information), the server could also return the URLs of possible actions, such as to deposit, withdraw, etc., as we can see in the following example (Wikipedia, 2021).

HTTP/1.1 200 OK

“account”: {
“account_number”: 12345,
“balance”: {
“currency”: “usd”,
“value”: 100.00
“links”: {
“deposits”: “/accounts/12345/deposits”,
“withdrawals”: “/accounts/12345/withdrawals”,
“transfers”: “/accounts/12345/transfers”,
“close-requests”: “/accounts/12345/close-requests”

Currently, there are no general-purpose standards that define how to model the HATEOAS principle (Price E., et al., 2018). From my perspective, the most controversial and challenging to follow REST constrain is the HATEOAS. It adds a lot of complexity to the server project, and sometimes the clients do not use it. For that reason, several backend developers do not apply it. In such cases, the APIs are referred to as REST-Based (.NET Nakama, 2021 September).

Using HATEOAS offers several advantages, such as (SOA Bits and Ramblings, 2013):

Explorable APIs,
Inline documentation,
Simpler client logic,
Server ownership of URL structures,
Easier versioning in the URI.

However, let’s keep in mind the key-point of “Do Not Follow the API-Best-Practices Blindly” (.NET Nakama, 2021 September) and the “Keep It Simple Stupid (KISS)” principle. Based on the needs of our clients and our project’s requirements, we should examine if the HATEOAS is worth implementing and then decide. Do not just try to make a RESTful API just for the name!

Tip: Do not just try to make a RESTful API just for the name!


Caching is the process of temporarily storing data or files in storage to be accessed more quickly. This process is used when the computation or/and the retrieval of the data or files require significant time or/and resources (e.g., CPU, network bandwidth, etc.). However, it is essential to cache data or files for a duration related to each case (how frequently the specific data changes, its importance, etc.) because otherwise, they might be outdated (staled).

In client-server communication, we can perform caching on both sides for different reasons.

In the server: We could cache (in Redis, MemoryCache, etc.) the data retrieved from a database or a third-party system to faster respond to the client.
In the client: We could cache the retrieved data from the server to reduce the following requests.

The cache constraint in the REST architectural style is related to client caching guided by the server using HTTP headers to label the response data as cacheable or non-cacheable. In this way, the client can reuse the same data in later equivalent requests (usually for a limited timeframe), with partial or no interaction with the server (.NET Nakama, 2021 September). The HTTP client caching is generally performed for the GET HTTP requests.

In the following sections, we will focus on the response HTTP headers that guide the clients caching.


The Cache-Control header value (RFC-7234) can contain several directives (comma separated) to configure the caching policies of the requests and responses. The main idea is to cache the response until it becomes stale (based on the Cache-Control directives and the Expires HTTP Header). After that, stale resources can either be validated or fetched again (see Cache Validation section).

The following table presents the most common Cache-Control directives (Fielding R. et al., 2014).


Cache-Control: no-store
A cache must not store any part of either the immediate request or response.

Cache-Control: no-cache
The response must not be used to satisfy a subsequent request without successful validation on the server (it is always stale). In case it is used on a request, the server should regenerate the response for the client and store it in its cache.

Cache-Control: public
Any cache may store the response.

Cache-Control: private
The response message is intended for a single user and must not be stored by a shared cache. However, a private cache may store and reuse the response.

Cache-Control: max-age=5
Determine the number of seconds (e.g., five in the example) that a response can be cached. After that period, the cached value is considered stale.

Cache-Control: must-revalidate
This indicates that once the cache has become stale, it cannot be used as a cached response to satisfy subsequent requests without successful validation on the origin server.

Expires HTTP Header

The Expires HTTP header contains the date/time after which the response is considered stale. In general, staled resources should not be used (, 2021). If a Cache-Control header exists with a max-age directive in the response, then the Expires header is ignored.

Cache Validation

When a resource is staled (expired), it can either be validated or fetched again. The validation is performed to the server by providing some information in the request (as HTTP headers) about the specific resource (e.g., an identifier or the last modification date).

This information is provided by the server (in the original response) as HTTP headers, and specifically, it is the ETag and the Last-Modified.


The ETag HTTP response header is an identifier for a specific version of a resource. This identifier is usually a hash of the resource (see the following example). Thus, when the resource changes (different versions of the data), a new hash is generated.

ETag: “e4d16978735c9e008be608c3a7eb59a89b277fe7ffd6744b655006065de88d75”

Using the ETag value in an “If-None-Match” header to the following GET requests, the server can save network bandwidth by not resending the complete response when the content was not changed. In such cases, the server returns a 304 Not Modified HTTP status code which is used as a 200 OK response telling the client to use the cached resource.

If-None-Match: “e4d16978735c9e008be608c3a7eb59a89b277fe7ffd6744b655006065de88d75”

Also, when transferring resources to the server, cache validation can be performed (e.g., POST, PUT, etc.) by sending the ETag value in an “If-Match” header. The server will compare the provided ETag value with the current resource ETag value, and if they match (i.e., it has not changed in the meantime), the update will be performed. On the other hand, if the ETag values do not match, the server will respond with a 412 Precondition Failed HTTP status code.

If-Match: “e4d16978735c9e008be608c3a7eb59a89b277fe7ffd6744b655006065de88d75”


The Last-Modified response HTTP header contains a date and time when the server believes the resource was last modified. It is used similarly with the ETag HTTP header, but it is less accurate.

Last-Modified: Wed, 20 Oct 2021 06:17:00 GMT

The Last-Modified value can be used in the same way in correspondence with the ETag value by using the following HTTP headers: If-Unmodified-Since and If-Modified-Since.


This article focused on HTTP status codes, Media Types, HATEOAS, and Caching to improve our REST Web APIs. Decisions on these topics can influence our Web APIs usability, extensibility, and performance.

The consistent and meaningful use of the HTTP status codes can make a huge difference in our API’s usability. For example, the server would inform better the API consumer applications and their developer(s) about what happened to perform the appropriate actions in case of errors.

Using HATEOAS offers several significant advantages regarding extensibility. However, it adds a lot of complexity, and sometimes the clients do not use it. Therefore, we should examine if the HATEOAS is worth implementing in each project separately and then decide. We should not just try to make a RESTful API just for the name!

Caching can improve the performance of our applications by temporarily storing data or files to be accessed more quickly. The cache constraint in the REST architectural style is related to client caching guided by the server. For that purpose, we examined the response HTTP headers that guide the clients caching.

There will always be space for improvement in our Web APIs and software development in general. However, we can continuously improve our technical skills, understand how things work, and gain experience, reflecting in our code and decisions.


.NET Nakama (2021, September 4). Designing a RESTful Web API.

Fielding R., et al. (2014, June). Hypertext Transfer Protocol (HTTP/1.1): Caching.

Lock A. (2017, August 01). How to format response data as XML or JSON, based on the request URL in ASP.NET Core. (2021, October 20). HTTP caching.

SOA Bits and Ramblings (2013, December 06). Selling the benefits of hypermedia in APIs.

Price E., et al. (2018, December 1).RESTful web API design.

Wikipedia (2021, October 10). HATEOAS.

Announcing ASP.NET Core in .NET 6

.NET 6 is now released! ASP.NET Core in .NET 6 includes everything you need to build rich modern web UI and powerful back-end services.

What’s new?

Here’s a sampling of the great new features and improvements in ASP.NET Core for .NET 6:

Hot reload: Apply changes to Razor, C#, and CSS source files into your running app during development without the need to rebuild and restart the app.

Minimal APIs: Create a new ASP.NET Core app with just a few lines of code using the latest C# features and a simplified hosting model.

Async streaming: Asynchronously stream data from the server without any need for buffering.

IAsyncDisposable: Support for IAsyncDisposable on controllers, page models, and view components.

Bootstrap 5.1: ASP.NET Core now comes with integrated Bootstrap 5.1 support.

Null-state analysis: All ASP.NET Core templates now have C# null-state analysis enabled by default.

CSS isolation for pages and views: Scope CSS styles to specific pages or views using .cshtml.css files.

JavaScript modules: Place related JavaScript modules alongside pages, views, and components using .cshtml.js and .razor.js files.

Blazor improvements:

Render components from JavaScript
Preserve prerendered state
Error boundaries
Custom event args
Infer generic type parameters from ancestor components
Required component parameters
Handle query string parameters
Control HTML head content
JavaScript initializers
Dynamically render components

.NET WebAssembly build tools: Ahead-of-time (AOT) compilation for Blazor WebAssembly apps, as well as support for runtime relinking and native dependencies.

Single-page apps: Built-in support for Angular 12 and React 17 based on a flexible template pattern that can be used with other popular frontend JavaScript frameworks.

Socket control: More control over socket creation and handling.

Strongly-typed headers: Accessing HTTP headers in a strongly-typed way.

HTTP & W3C logging: Log HTTP traffic, and log using the W3C Extended Log File Format.

HTTP/3 (Preview): Preview of server support for HTTP/3 based on the new QUIC transport.

For a full list of everything that’s new in ASP.NET Core in .NET 6, check out the ASP.NET Core in .NET 6 release notes.

Get started

To get started with ASP.NET Core in .NET 6, install the .NET 6 SDK. .NET 6 is also included with Visual Studio 2022. Mac users should use the latest Visual Studio 2022 for Mac preview.

Upgrade an existing project

To upgrade an existing ASP.NET Core app from .NET 5 to .NET 6, follow the steps in Migrate from ASP.NET Core 5.0 to 6.0

To upgrade an existing ASP.NET Core app from .NET 6 RC2 to .NET 6, update all package references to 6.0.0.

That’s it! You should be all set to enjoy the benefits of .NET 6.

See also the full list of breaking changes in ASP.NET Core for .NET 6.

Join us for the .NET 6 release at .NET Conf 2021

Come celebrate with us and learn all about the .NET 6 release at .NET Conf 2021, a FREE, three day virtual developer event with over 80 sessions featuring speakers from the .NET team and the broader .NET community. The conference starts tomorrow and goes from November 9-11. We hope you can join us!

Azure Functions, Web Apps, and Static Web Apps support .NET 6

Azure App Service teams have been working around the clock to make sure .NET 6 is supported across your favorite Azure PaaS services like Web Apps and Functions, so you don’t have to wait to deploy. At the time of this post, .NET 6 is being actively deployed to the worldwide network of servers and configured to build and run .NET 6 apps.

For more information on the various Azure services and their roll-out of supporting .NET 6, which should conclude by the end of this week, see the following links:

Azure Functions now supports running serverless functions in .NET 6

The App Service .NET 6 GA Announcement has information and details for ASP.NET Core developers excited to get going with .NET 6 today. One thing to note – if you’re already running a .NET 6 preview build on App Service, your app will be auto-updated on the first restart once the .NET 6 runtime and SDK are deployed to your region – you don’t have to rebuild or do anything, it’ll just update if you’re not running a self-contained app.
Azure Static Web Apps now supports full-stack .NET 6 applications with Blazor WebAssembly frontends and Azure Function APIs

We’re sure you’ll enjoy the immediate availability of Azure App Service to run your ASP.NET Core and Serverless .NET apps. And don’t forget to try using Azure Container Apps if you’re keen on building some background microservices using the .NET Core Worker Service template, too.

Thank you!

Thank you to everyone in the community who helped make this release of .NET 6 possible! This release represents the culmination of many GitHub issues, pull requests, design feedback comments and documentation updates contributed by many members of the .NET community. We couldn’t have made it to this point without you!

We hope you enjoy this release of ASP.NET Core in .NET 6. We’re eager to hear about your experiences building with it. Let us know about your creative efforts on GitHub.

Thanks again, and happy coding!

The post Announcing ASP.NET Core in .NET 6 appeared first on .NET Blog.

Flatlogic Web App Generator+GitHub!

 Hello coders!

Our full-stack web app generator got integration with well-known and well-liked GitHub. Now you can add projects to your GitHub account where you will see a repository with the project made on the web app generator. If you make an update to your project in the generator, all the updates will be pushed to the repository.

Thanks to GitHub version control, you will be able to keep track of all your changes made to the source code. All the changes in your generated project will be saved and shown in the appropriate repository in your GitHub account! This way you synchronize and closely monitor your tests and projects from Web App Generator with GitHub.

Setting Up

How to make it work?

Connect your GitHub account in the project settings.

How to generate a project with web app generator?

Let us recall how to work with the web app generator step by step:

Choose the technology stack for your project: React, Vue, Angular – for the frontend part,
Laravel, Node.js – for the backend part and MySQL, PostgreSQL for database;
Choose the design you like;
Define the database schema;
Generate your application, get the source code and download it!

Check our recent blog posts to know more on the web app generator

Code preview added
Laravel Backend Released
Launching Web App Generator

The post Flatlogic Web App Generator+GitHub! appeared first on Flatlogic Blog.