Skip to main content

Posts

Showing posts with the label REST

Data API Builder - Get a visual config UI

With the Data API builder, you can easily generate an API on top of an existing database. However typing out the configuration settings in the dab-config.json isn't much fun. The auto-entities features I talked about before can certainly help, but that is not always the right solution. With the integrated GUI in the MSSQL extension for Visual Studio Code, you can replace the manual JSON configuration with a visual interface that handles entity selection, CRUD permission mapping, API type targeting, and Docker-based local deployment — all without leaving the editor. This post covers exactly what the UI does, what it generates, and where it falls short. Entry points The DAB configuration view is accessible from two places: Object Explorer — right-click a database node → Build Data API (Preview)... Schema Designer — Design API button (top-right toolbar) or the Backend icon in the left panel Both open the same configuration surface. Entity selection Tables a...

DAB 2.0 Preview: Autoconfiguration with autoentities

If you've been maintaining a large dab-config.json , you know the pain: every table, view, and stored procedure needs its own entities block. Schema grows, config grows. Someone adds a table and forgets to update the config, and suddenly your API is silently missing endpoints. DAB 2.0 Preview introduces autoentities — a pattern-based approach that discovers and exposes database objects automatically, every time DAB starts. This post covers how it works, how to configure it from the CLI, and what to watch for. Getting started As DAB 2.0 is still in preview, you first need to install the preview version: dotnet tool install microsoft.dataapibuilder --prerelease Note: MSSQL data sources only, for now. Initialize a new dab-config.json file if it doesn't exists yet: dotnet dab init Remark:  Notice that we prefix dab with dotnet to avoid collisions with the globally installed release version. How it works Instead of defining each entity explicitly, you define one ...

Use request chaining in HTTP files

By default every request inside your HTTP file is independent from any other request. But what if you want to use the output of one request as the input of another request? This is exactly what you can achieve using request variables. Creating resources with dependencies As an example I created a new ProjectController that we will use to: Create a new project Use the returned project id to create and assign a new task to this project I updated the http file with a new request to create the project. Notice that I included a createProject variable to name the request. I can now use this createProject variable in other requests. In our example I extract the project id value from the response: The following table describes the syntax in more details: Element Description requestVarName ( login in this case ) Request Variable which is being referenced. response|request Whether the value will be...

Use shared variables in HTTP files

Yesterday I explained how you can introduce environment specific variables when using .http files in Visual Studio. But now we need to repeat these variables for every environment even when they stay the same. In this post I show how to avoid this by introducing the special $shared environment. The $shared environment Visual Studio 2022 version 17.12 introduced the $shared environment, which is perfect for variables that should be available across all environments: You can now use these shared variables no matter which environment you have selected: More information Use .http files in Visual Studio 2022 | Microsoft Learn

Use environment specific variables in HTTP files

HTTP files provide a convenient way to test your API’s inside Visual Studio. In this post we'll look at a specific feature; the usage of environment-specific variables that let you seamlessly switch between environments without modifying your request files. Getting started with .http files Before diving into environment variables, let's understand the basics. When you create an ASP.NET Core project in Visual Studio 2022, you'll often find a .http file already in your solution. Here's a simple example: Variables are defined with @variableName = value and referenced using {{variableName}} . The ### delimiter separates multiple requests in a single file. Creating environment files The real power comes when you externalize these variables into environment files. Visual Studio supports two types of environment files: 1. http-client.env.json (Shared) This file contains environment configurations that are shared across your team and typically committed to sourc...

Detecting breaking changes in your OpenAPI metadata

For the last 2 days I have been struggling with a breaking change I had in my ASP.NET Core web api that caused the consuming application to fail. I had a header parameter that was optional but became required after changing the nullability of my project to enabled . Although I found the issue and was able to fix it quite fast, I was not happy with my current process and was wondering how I could prevent this from happening again. This brought me to a final solution where I introduced some extra tests that compared the OpenAPI metadata between different implementations. Let me show you how I did it… Generate OpenAPI documents at build time To compare 2 OpenAPI metadata documents we first need to get them. For the already released version of the API, I can download the document through the OpenAPI endpoint ( /openapi/v1.json by default). But what about the new version of the API that is still in development? I solve this by generating the OpenAPI document at build time. This m...

.NET 9–OpenAPI and Scalar–Passing an API key

Let's continue our joruney in discovering Scalar . Today I want to talk about how we can integrate security. Most API's that we build today are secured in a way. This could be as simple as an API key or as complex as using OAuth with PKCE. In this post we’ll look at how to pass an API key through the Scalar UI. Let’s dive in… I assume that you already have registered an authentication scheme for your API like this: Now we need to write an extra transformer to include the authentication information in our OpenAPI metadata. Don’t forget to register this transformer in our OpenAPI configuration: At the Scalar level we don’t have to change anything: But if we now browse to the Scalar UI, the authentication scheme is recognized and we get the option to pass an API key:   Nice! More information .NET 9–OpenAPI and Scalar–Introduction .NET 9–OpenAPI and Scalar–Adding custom headers

.NET 9–OpenAPI and Scalar–Adding custom headers

In this post I continue my investigation of using Scalar as an alternative to Swashbuckle that I was using before to expose my OpenAPI metadata in a userfriendly way. If you have no idea what Scalar is, I would recommend to check out my introduction post first before you continue reading. Today I want to have a look at how we can transform the OpenAPI metadata. On this specific API, it is expected that one of a set of custom headers is passed when calling the API. To simplify the experience, I originally created  an IOperationFilter for Swashbuckle to show these extra headers: How to customize the OpenAPI metadata in .NET 9? The generated OpenAPI document can be customized using “transformers”, which can operate on the entire document, on operations, or on schemas. Transformers are classes that implement the IOpenApiDocumentTransformer , IOpenApiOperationTransformer , or IOpenApiSchemaTransformer interfaces. Each of these interfaces has a single async method that receives...

.NET 9–OpenAPI and Scalar–Introduction

With the release of .NET 9 , Microsoft has removed Swashbuckle from the default Web API templates. If you have never heard about Swashbuckle before, it allowed you to generate OpenAPI metadata for your web api's. Although I had no complaints using the Swagger UI, I decided to use the opportunity to have a look at library, Scalar, to generate an UI based on the OpenAPI documentation. In this post, I’ll walk you through my transition from Swashbuckle to Scalar, highlighting the benefits, challenges, and key implementation steps. Why the change? Microsoft decided to drop Swashbuckle due to maintenance issues and a shift toward integrated OpenAPI support . While Swashbuckle provided automatic documentation , Swagger UI integration , and customizability , Scalar introduces a sleek UI , mobile-friendly interface , and enhanced search capabilities . Scalar not only provides great integration for .NET but also works on a lot of other platforms. Setting Up Scalar in .NET 9 To i...

Azure Static Web App–Data API Builder

As a follow-up on the presentation I did at CloudBrew about Azure Static Web Apps I want to write a series of blog posts. Part I - Using the VS Code Extension Part II - Using the Astro Static Site Generator Part III  – Deploying to multiple environments Part IV – Password protect your environments Part V – Traffic splitting Part VI – Authentication using pre-configured providers Part VII – Application configuration using staticwebapp.config.json Part VIII – API Configuration Part IX – Injecting snippets Part X – Custom authentication Part XI – Authorization Part XII -  Assign roles through an Azure function Part XIII -  API integration Part XIV – Bring your own API Part XV – Pass authentication info to your linked API Part XVI – Distributed Functions Part XVII(this post) – Data API Builder So far I have shown you 2 different possibilities to integrate an API inside your Azure Static Web App: You...

Using Problem Details in .NET 7

When comparing API's, I see a lot of different ways how error messages are returned. With the introduction of Problem Details for HTTP APIs ( https://tools.ietf.org/html/rfc7807 ) , we finally have a standardized error payload to return when an unhandled exception occurs. Although the standard was introduced before .NET 7, there was no out-of-the-box way to introduce the ProblemDetails spec into your ASP.NET Core application. A solution was to use the third party Hellang.Middleware.ProblemDetails nuget package: Starting from .NET 7 this nuget package is no longer necessary. You only need to add the following line to your service configuration: If someone now calls your API and an exception occurs, the returned result will look like this: We can further customize the behavior through CustomizeProblemDetails : More information Handle errors in ASP.NET Core web APIs | Microsoft Learn

Angular–Generate your OpenAPI client model

Most Angular applications need some kind of data typically provided through an OpenAPI or GraphQL API. Manually creating all the necessary model classes and client can be a time-consuming and error-prone task. In this post we have a look at ng-openapi-gen to help you automate this process. We start by installing the ng-openapi-gen module by executing the following command: npm install -g ng-openapi-gen Now we can generate our models and web client in the Angular application using the following command: ng-openapi-gen --input <path-to-openapi-json> --output <angular-app-path>/src/app/shared/api If you look at the command above you see that it requires to an OpenAPI specification file. This can be in JSON or YAML format. So we first need a way to get this specification file. If you are using ASP.NET Core with the OpenAPI integration , you can either download the OpenAPI file manually by going to the swagger UI and download it there or you can generate the OpenAPI...

Sending and receiving JSON data

In almost every application today you need to interact with REST api's typically using JSON as the serialisation format. During some code reviews I noticed the following boilerplate code coming back: Although there is nothing wrong with the code above, it is code that you don't have to write yourself. As this is such a common scenario, Microsoft created the System.Net.Http.Json NuGet package with the release of .NET 5.0. This package contains extension methods on the HttpClient object that take care of a variety of scenarios for you, including handling the content stream, validating the content media type and handling the deserialization. Using this package, you no longer need to write all this logic yourself and you can rewrite the code above to the following: Hope that helps!

Visual Studio 2022 17.6–Http Endpoint explorer

I occasionally switch to Jetbrains Rider and Visual Studio Code, but my favorite IDE is and remains Visual Studio(especially with the Github Copilot integration ).  With the 17.6 release a new feature was introduced; the Endpoints explorer. With the Endpoints explorer, you can view and interact with the API endpoints defined in your solution. To use this feature go to View –> Other Windows –> Endpoint Explorer: You get an overview of all the API endpoints available in your solution and the available API calls that can be made: If you right click on an API call, you can choose between Open in the editor to jump to the implementation of the API call or Create Request . This will create a new HTTP file that can be used to execute the specific request on the endpoint: Nice!

Visual Studio–Generate C# client for OpenAPI

There are multiple ways to generate a C# client based on an OpenAPI specification file. Today I want to show you how this can be done directly inside Visual Studio. To import an OpenAPI reference, you can right-click on your project and choose Add –> Service Reference : Choose OpenAPI from the list of possible service references and click on Next: Now we can specify the details to our OpenAPI JSON file. Click on Finish to generate the client: It can take some time to generate the client. So be patient. What is happening behind the scenes? Let us have a look at all the things that Visual Studio is doing behind the scenes. First a copy of the OpenAPI json file is imported into our project and stored inside an OpenAPIs folder: On this JSON file the build action is set to Open API File Reference and specific code generation attributes are configured: Our updated csproj file looks like this: Behind the scenes the code generator is using the Microsoft....

Azure - Data API Builder

While browsing through Github, I discovered the following project: Data API builder for Azure Databases (DAB). With data API builder, database objects can be exposed via REST or GraphQL endpoints so that your data can be accessed using modern techniques on any platform, any language, and any device. With an integrated and flexible policy engine, native support for common behavior like pagination, filtering, projection and sorting, the creation of CRUD backend services can be done in minutes instead of hours or days, giving developers an efficiency boost like never seen before. Sounds cool and a perfect fit for a small application where you only need an API to expose some data. Let’s give it a try! Setup Data API builder provides a CLI tool to help us with the configuration and the setup of our project. Install the tool using the following command: dotnet tool install --global Microsoft.DataApiBuilder Now that the tool is installed successfully, we need to create a co...

Executing HTTP requests through Visual Studio

In Visual Studio 2022 v17.5, a new feature was introduced that allowed you to execute HTTP requests directly from the Visual Studio IDE. This is great of you want to test an API endpoint without leaving your IDE. To use this feature, open a Visual Studio project, right click on it and choose Add –> New Item . Search for http to find the HTTP file template , specify a name and click on Add . Now we can start writing our HTTP requests inside this file. You even get Intellisense while building up your requests. Once you are done, you can either click on the play icon next to the line or right click on the line and choose Send Request from the context menu. It is possible to have multiple calls in the same file, therefore separate your requests with a comment line using three hashes: You can also create variables by prefixing them with an @ and use these variables using double curly braces:  

ASP.NET Core API Versioning

A lot has been written about API versioning and the opinions differ on what the 'best' approach is. I'm not planning to add an extra opinion to the mix, instead I want to focus on one of the ways you can do API versioning in ASP.NET Core. Versioning by content type When using versioning by content type, we use custom media types instead of generic types such as application/json . To make this work we can rely on content negotiation inside our API. Here is an example: Accept: application/vnd.example.v1+json Accept: application/vnd.example+json;version=1.0 Inside our ASP.NET Core controllers, we have to introduce the [Consumes] attribute. This attribute allows an action to influence its selection based on an incoming request's content type by applying a type constraint. What about Minimal API’s? At the moment of writing, ASP.NET Core Minimal API’s don’t support content negotiation (yet).

API Design in ASP.NET Core Part II

This week I had the honor to give a training to some of the newly started young professionals in our organisation. The topic of the training was API design in ASP.NET Core. During this training we discussed multiple topics and a lot of interesting questions were raised. I'll try to tackle some of them with a blog post. The question I try to tackle today is... When do I know that my Web API is truly RESTful? Yesterday I introduced the concept of REST and mentioned that it was an architecture style. As a result you’ll find a lot of different flavors of Web API’s in the wild each using a different approach and all calling themselves REST API’s. To help you answer the question above, we can use the Richardson Maturity Model . Leonard Richardson analyzed a hundred different web service designs and divided these designs into four categories . These categories are based on how much the web services are REST compliant . He used three main factors to decide the maturity of a ...