0% found this document useful (0 votes)
0 views

Minimal API (1)

Minimal APIs in .NET 8 provide a streamlined approach to creating HTTP APIs, focusing on simplicity, performance, and reduced code overhead. They allow developers to define endpoints directly in the Program.cs file, making them suitable for small-scale microservices and applications. Key features include built-in dependency injection, flexible routing options, and ease of setup, distinguishing them from traditional controller-based APIs.

Uploaded by

mprathap102
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Minimal API (1)

Minimal APIs in .NET 8 provide a streamlined approach to creating HTTP APIs, focusing on simplicity, performance, and reduced code overhead. They allow developers to define endpoints directly in the Program.cs file, making them suitable for small-scale microservices and applications. Key features include built-in dependency injection, flexible routing options, and ease of setup, distinguishing them from traditional controller-based APIs.

Uploaded by

mprathap102
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Minimal API with .

net 8
What is Minimal API?

Minimal APIs are a simple way to create HTTP APIs in .NET. They are designed to
simplify the definition and handling of HTTP requests compared to current ASP.NET Core
methods. They work well for small-scale microservices, focusing on minimizing unnecessary
code and using a straightforward programming model.

Key Features of Minimal APIs

 Conciseness: Minimal APIs reduce the amount of unnecessary code, allowing you to
define endpoints directly in the Program.cs file or other single files.

 Performance: The reduced overhead of Minimal APIs may result in faster startup times
and lower memory usage, making them suitable for high-performance scenarios.

 Simplicity: These APIs are easy to set up and manage with minimal configuration,
making them a great choice for simple applications or microservices.

 Flexibility: They offer a wide range of HTTP methods and routing options, providing a
flexible approach to defining endpoints.

 Built-in Dependency Injection: Minimal APIs, like other .NET APIs, use the built-in
dependency injection system to manage dependencies.

Minimal API example

A simple example of an API that adds three decimal places and returns the result as a
response has been made by me. Another API takes three values and returns the result as a
response. The functionality of these two APIs is carried out by means of two distinct logics. In
order for us to discuss "class" and "record" in this instance. The program.cs file contains all
of the code for these APIs in this example.
 First, in program.cs file adding the below code to create a builder for the web application.

Here, initializing a new instance of the WebApplicationBuilder class, which is


used to configure services and middleware for the application. The args parameter
allows passing command-line arguments to the application.

 Then, Registering services

 Registering the CalculatorService class as a singleton service in the


application's dependency injection container. A singleton service is created once
and shared throughout the application.
 AddSingleton is a method used to register a service with the dependency
injection (DI) container.
 Lifetime Management: When you use AddSingleton, it registers the service so
that only a single instance of the service is created and shared throughout the
application's lifetime. This means that every time the service is requested
(injected) by the application, the same instance will be provided.
 Usage: In this example,
builder.Services.AddSingleton<CalculatorService>();, the
DI container to create and manage a single instance of CalculatorService.
This instance will be shared across the entire application wherever
CalculatorService is injected.
 Implementation: This is particularly useful for services that are stateless or where
maintaining a single shared instance is beneficial for performance or consistency
reasons. For example, a configuration service or a logging service might be
implemented as a singleton.
 Adding services to the container

 AddEndpointsApiExplorer(): Adds support for generating API


documentation by exploring endpoints. This is useful for generating metadata for
tools like Swagger.
 AddSwaggerGen(): Registers the Swagger generator service, which
automatically generates documentation for your API endpoints.
Swagger: A web-based UI that provides a visual representation of your API’s
documentation. It allows users to interact with your API endpoints directly from the
browser. They can view available endpoints, their parameters, and try out requests and
responses.

 Creates and configures an instance of the WebApplication class based on the settings
and services defined in the builder object.

Builds the WebApplication instance from the configuration provided by the


WebApplicationBuilder. This instance represents the web application and is used to
configure the HTTP request pipeline.

 Next, Configuring the HTTP request pipeline.

Configures middleware based on the application's environment. In development


environments:
 app.UseSwagger(): Adds middleware to serve the Swagger JSON document.
 app.UseSwaggerUI(): Adds middleware to serve the Swagger UI, which
provides a web-based interface for interacting with the API.

 Now defines a route for a GET request in a Minimal API application. Minimal APIs in
ASP.NET Core provide a streamlined way to define and handle HTTP requests with less
boilerplate code compared to traditional controller-based approaches

 app.MapGet: This method is used to map an HTTP GET request to a specific


route and associate it with a handler function. In this case, the route is
/v/1/getAddResult.
 Route: "/v/1/getAddResult" - This is the URL path that clients will use to
make a GET request.
 Handler Function: The lambda function (decimal val1, decimal val2,
decimal val3, CalculatorService service) => {} is the logic
that will execute when a request is made to the specified route.
 CalculatorService service: This is a dependency injected into
the handler. It’s an instance of CalculatorService, which provides
methods to perform calculations.
 Asynchronous Operation: The handler function is marked as async,
indicating it performs asynchronous operations. It calls await
service.GetAddResult(val1, val2, val3), which
presumably makes an asynchronous call to get the result of adding the
three decimal values.
 Results.Problem(ex.Message) returns a problem response with
the exception message.
 .WithName("GetAddResult"): This method gives the route a
name. Naming routes can be helpful for generating URLs or referencing
the route in documentation. It provides a way to identify this particular
endpoint within the API.
 For Run the application

Starts the web application and begins listening for HTTP requests.

 Declaring the Service class

 Class Definition: This defines a class named CalculatorService that is


intended to encapsulate methods for performing calculations. The public
keyword indicates that this class is accessible from other parts of the application.
 async Task<CalcValues>: This indicates that the method is asynchronous
and returns a Task that will eventually yield a CalcValues object. The Task
class is used for asynchronous programming in .NET.
 Async/Await: The async keyword suggests that this method is designed to be
asynchronous, though no await is used within it. The method could be modified
to include asynchronous operations (e.g., database calls) in the future.
 Adding model class

A class defining a changeable data structure with a single property result that can be set
and retrieved

 Adding record

A record defining a changeable data structure with a single read-only property result. The
value is set through the constructor and cannot be changed afterward.

Key Point:
o Class is a changeable class that has constructors, extra methods, and properties. Ideal in
situations when changing an object's attributes after creation is necessary.
o Record: This data structure definition syntax is simple and unchangeable by default.
Ideal in situations when value-based equality and an immutable object are required.

Minimal API example with Repository

Using the same calculator service as an example, I developed a repository class and
moved the logical functionality to it. In order to use the repository class and its functionality
within the program, AddSingleton must be used to register the repository's services.

 For this, in Program.cs to create a builder for the web application.


Uses of WithName

 The endpoint is assigned a specific name, making it easier to generate URLs


programmatically within application. This is particularly useful for creating links or
redirects without hardcoding the URL paths.
 Assigning meaningful names to routes makes your code more readable and easier to
identify the purpose of each endpoint.
 If you need to change the URL path of an endpoint, you only need to update it in one
place. The named route remains the same, so all references to the named route will still
work correctly
 Named routes can be used to generate links in Razor Pages or MVC Views, making it
easier to create navigation links that are robust to changes in URL paths.
<a href="@Url.RouteUrl("GetSubResult")">Get Subtraction
Result</a>
 Enhance API documentation clarity.

Token Validation in Minimal API

FluentValidation.AspNetCore

Used for adding custom validations using RuleFor and its will return error messages if the
validation is failed.
Differences Between Minimal APIs and Controller-Based APIs

1. Code Structure:

o Minimal APIs: You can define it directly in Program.cs or a similar file using a
concise, functional style, without the need for separate controller classes.

o Controller-Based APIs: Using separate controller classes with attributes creates a


more traditional and detailed structure.

2. Setup and Configuration:

o Minimal APIs: Setting up is easy with minimal configuration required. You can
define routes and handlers directly within the code.

o Controller-Based APIs: Setting up the controllers and action methods requires


some additional setup. There's also a bit more work needed for routing and
attribute configuration.

3. Dependency Injection:

o Minimal APIs: Setting up dependency injection is easy and you can configure it
directly in the Program.cs file.

o Controller-Based APIs: Controllers often handle dependency injection, typically


involving a lot of extra code.

4. Routing:
o Minimal APIs: Routing is defined more simply using lambda expressions or
method chains.

o Controller-Based APIs: Routing is configured using attributes and routes defined


at the class and method levels.

5. Middleware:

o Minimal APIs: Middleware can be set up and applied inline, making it easier to
see the entire request handling pipeline.

o Controller-Based APIs: Middleware is often configured globally or in specific


parts of the application, which may require more navigation through different
files.

You might also like