0% found this document useful (0 votes)
2 views7 pages

minimal api

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 7

Minimal APIs in C# are a feature introduced in ASP.NET Core 6.

0 that allows
developers to create lightweight, self-contained HTTP services with minimal
ceremony. It provides a simpler and more concise syntax for defining
endpoints compared to traditional ASP.NET Core MVC controllers.

### Key Features of Minimal APIs:

1. **Lightweight Syntax**: Minimal APIs use a simplified syntax that requires


fewer lines of code compared to traditional MVC controllers, making them
ideal for small or simple HTTP services.

2. **No Controller Classes**: With minimal APIs, you don't need to define
controller classes. Instead, you define routes and handlers directly within the
application's startup code.

3. **Convention-based Routing**: Minimal APIs use convention-based


routing, which means that routes are defined based on HTTP methods and
URL patterns.

4. **Use of Delegates**: Handlers for HTTP endpoints are defined using C#


lambda expressions or delegate methods, allowing for a more concise and
expressive syntax.

### Example of Minimal API:

Here's an example of a minimal API defined in a C# application's startup


code:

```csharp

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();


app.MapGet("/hello", () => "Hello, World!");

app.Run();

```

In this example:

- `WebApplication.CreateBuilder(args)` creates a builder object for


configuring the application.

- `app.MapGet("/hello", () => "Hello, World!")` defines a route for handling


HTTP GET requests to the "/hello" endpoint. The lambda expression `() =>
"Hello, World!"` serves as the handler for the endpoint, returning a string
response.

- `app.Run()` starts the application and begins listening for incoming HTTP
requests.

### Benefits of Minimal APIs:

- **Simplicity**: Minimal APIs offer a simpler and more lightweight alternative


to traditional MVC controllers, reducing the overhead associated with
defining and configuring controllers and actions.

- **Reduced Boilerplate**: With minimal APIs, there's less boilerplate code to


write and maintain, resulting in cleaner and more concise codebases.

- **Fast Startup**: Minimal APIs contribute to faster application startup times


since there's less overhead involved in initializing controllers and middleware
components.
- **Ease of Learning**: Minimal APIs are easier to learn and understand for
developers who are new to ASP.NET Core or web development in general, as
they require fewer concepts and conventions to grasp.

Overall, minimal APIs provide a streamlined and efficient way to build HTTP
services in C# with ASP.NET Core, particularly for small-scale projects or
microservices where simplicity and speed of development are paramount.

In ASP.NET Core 6.0, you can implement minimal APIs for Employee and
Customer controllers using a simplified syntax. Below is an example of how
you can define minimal APIs for both controllers:

```csharp

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

// Define routes for Employee Controller

app.MapGet("/employees", () => "Get all employees");

app.MapGet("/employees/{id}", (int id) => $"Get employee with ID: {id}");

app.MapPost("/employees", () => "Create new employee");

app.MapPut("/employees/{id}", (int id) => $"Update employee with ID:


{id}");

app.MapDelete("/employees/{id}", (int id) => $"Delete employee with ID:


{id}");

// Define routes for Customer Controller

app.MapGet("/customers", () => "Get all customers");

app.MapGet("/customers/{id}", (int id) => $"Get customer with ID: {id}");


app.MapPost("/customers", () => "Create new customer");

app.MapPut("/customers/{id}", (int id) => $"Update customer with ID:


{id}");

app.MapDelete("/customers/{id}", (int id) => $"Delete customer with ID:


{id}");

app.Run();

```

In this example:

- For the Employee controller, routes for GET, POST, PUT, and DELETE
operations are defined for the endpoints "/employees" and
"/employees/{id}".

- Similarly, for the Customer controller, routes for GET, POST, PUT, and
DELETE operations are defined for the endpoints "/customers" and
"/customers/{id}".

Each route is associated with a lambda expression that handles the


corresponding HTTP request. The parameters in the lambda expressions
(e.g., `(int id)`) represent route parameters that can be extracted from the
request URL.

This is a basic example to illustrate how you can implement minimal APIs for
two controllers. You can extend this example to include more complex logic,
such as interacting with databases or external services, validating input
data, or implementing authentication and authorization.

Sure, here's a sample minimal API using Dapper to fetch data from an
Employee table in a SQL database:

```csharp
using Microsoft.AspNetCore.Builder;

using Microsoft.AspNetCore.Http;

using Microsoft.Extensions.DependencyInjection;

using System.Collections.Generic;

using System.Data;

using System.Data.SqlClient;

using System.Threading.Tasks;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddScoped<IDbConnection>(provider =>

var connectionString =
builder.Configuration.GetConnectionString("DefaultConnection");

return new SqlConnection(connectionString);

});

var app = builder.Build();

app.MapGet("/employees", async (IDbConnection dbConnection) =>

var employees = await dbConnection.QueryAsync<Employee>("SELECT *


FROM Employees");

return Results.Ok(employees);

});

app.Run();
public class Employee

public int Id { get; set; }

public string Name { get; set; }

public string Department { get; set; }

```

In this example:

1. We register `IDbConnection` with dependency injection, providing a


`SqlConnection` instance using the connection string from the application
settings.

2. We define a route for GET requests to "/employees". Inside the route


handler, we use Dapper's `QueryAsync` method to execute a SQL query and
retrieve all employees from the database. The result is returned as JSON.

3. We define a simple `Employee` class to represent the structure of


employee data retrieved from the database.

Ensure you have the required NuGet packages installed for Dapper and your
database provider (e.g., Microsoft.Data.SqlClient for SQL Server). Also, don't
forget to replace `"DefaultConnection"` with the name of your connection
string in the appsettings.json or appsettings.Development.json file.

This minimal API fetches all employee data from the Employees table in
response to GET requests to "/employees". You can further expand this API
to handle other CRUD operations, error handling, pagination, filtering, or
sorting as needed.

You might also like