.NET 9 Minimal Web API

REST API: What is it?

The acronym for REpresentational State Transfer is REST. This architectural approach establishes a set of guidelines for developing web services. REST recommends constructing an object with the client-requested data and responding to the user with the object’s values via a client-server conversation. For instance, you can make an object on the server side if the user is asking to book a taxi in Bangalore at a specific location and time. You have an object over here, and you are transmitting its status. REST stands for Representational State Transfer as a result.

The architectural style of REST helps in leveraging the lesser use of bandwidth to make an application more suitable for the Internet. It is often regarded as the “language of the internet” and is completely based on the resources.

Principles of REST API

Below are the six guiding principles of REST:

Stateless

The URL is used to uniquely identify the resource, and the body holds the state of the requested resource. Once the server processes the request, a response is sent to the client through body, status, or headers. The requests sent from a client to a server will contain all the required information to make the server understand the requests sent from the client. This can be either a part of the URL, query-string parameters, body, or even headers. No state is cached in the server API so every request is agnostic of each other. This REST behavior also helps in scaling the API service in the cloud environment.

Client-Server

The client-server architecture enables a uniform interface and separates clients from the servers. This enhances the portability across multiple platforms as well as the scalability of the server components.

Uniform Interface

To obtain uniformity throughout the application, REST has the following four interface constraints:

  • Resource identification
  • Resource Manipulation using representations
  • Self-descriptive messages
  • Hypermedia as the engine of application state

Cacheable

To provide a better performance, the applications are often made cacheable. This is done by labeling the response from the server as cacheable or non-cacheable, either implicitly or explicitly. If the response is denied as cacheable, then the client cache can reuse the response data for equivalent responses in the future.

Minimal APIs in NET 9 or .NET 8, or .NET 7

Minimal APIs are architected to create HTTP APIs with minimal dependencies. They are ideal for microservices and apps that want to include only the minimum files, features, and dependencies in ASP.NET Core.

Limitations of Minimal API

  1. No support for filters: For example, no support for IAsyncAuthorizationFilter, IAsyncActionFilter, IAsyncExceptionFilter, IAsyncResultFilter, and IAsyncResourceFilter.
  2. No support for model binding, i.e. IModelBinderProvider, IModelBinder. Support can be added with a custom binding shim.
  3. No support for binding from forms. This includes binding IFormFile. We plan to add support for IFormFile in the future.
  4. No built-in support for validation, i.e. IModelValidator
  5. No support for application parts or the application model. There’s no way to apply or build your own conventions.
  6. No built-in view rendering support. We recommend using Razor Pages to render views.
  7. No support for JsonPatch
  8. No support for OData
  9. No support for ApiVersioning. See this issue for more details.

With the following APIs,

REST APIs follow standard HTTP Verbs like GET, POST, PUT, DELETE, and PATCH, which are basically CRUD operations on an object. The APIs are arranged to form an internet resource. For example, in the above example, we have a resource as “todoitem” which can be created, modified, and deleted using APIs, and the URL format is formed accordingly.

using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext < TodoDb > (opt => opt.UseInMemoryDatabase("TodoList"));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.MapGet("/", () => "Hello World!");
app.MapGet("/todoitems", async (TodoDb db) => await db.Todos.ToListAsync());
app.MapGet("/todoitems/complete", async (TodoDb db) => await db.Todos.Where(t => t.IsComplete).ToListAsync());
app.MapGet("/todoitems/{id}", async (int id, TodoDb db) => await db.Todos.FindAsync(id)
    is Todo todo ? Results.Ok(todo) : Results.NotFound());
app.MapPost("/todoitems", async (Todo todo, TodoDb db) => {
    db.Todos.Add(todo);
    await db.SaveChangesAsync();
    return Results.Created($ "/todoitems/{todo.Id}", todo);
});
app.MapPut("/todoitems/{id}", async (int id, Todo inputTodo, TodoDb db) => {
    var todo = await db.Todos.FindAsync(id);
    if (todo is null) return Results.NotFound();
    todo.Name = inputTodo.Name;
    todo.IsComplete = inputTodo.IsComplete;
    await db.SaveChangesAsync();
    return Results.NoContent();
});
app.MapDelete("/todoitems/{id}", async (int id, TodoDb db) => {
    if (await db.Todos.FindAsync(id) is Todo todo) {
        db.Todos.Remove(todo);
        await db.SaveChangesAsync();
        return Results.Ok(todo);
    }
    return Results.NotFound();
});
app.Run();
class Todo {
    public int Id {
        get;
        set;
    }
    public string ? Name {
        get;
        set;
    }
    public bool IsComplete {
        get;
        set;
    }
}
class TodoDb: DbContext {
    public TodoDb(DbContextOptions < TodoDb > options): base(options) {}
    public DbSet < Todo > Todos => Set < Todo > ();
}

Conclusion

REST architecture style provides a standard way to arrange resources over the internet and a common way for clients to access and get the server data. Minimal API requires minimum code and a quick and easy way to create APIs that do not require Auth or that sit behind a gateway(with Auth) and have very minimal dependencies.

Best and Most Recommended ASP.NET Core 8.0.8 Hosting

Fortunately, there are a number of dependable and recommended web hosts available that can help you gain control of your website’s performance and improve your ASP.NET Core 8.0.8 web ranking. HostForLIFE.eu is highly recommended. In Europe, HostForLIFE.eu is the most popular option for first-time web hosts searching for an affordable plan.

Their standard price begins at only €3.49 per month. Customers are permitted to choose quarterly and annual plans based on their preferences. HostForLIFE.eu guarantees “No Hidden Fees” and an industry-leading ’30 Days Cash Back’ policy. Customers who terminate their service within the first thirty days are eligible for a full refund.

By providing reseller hosting accounts, HostForLIFE.eu also gives its consumers the chance to generate income. You can purchase their reseller hosting account, host an unlimited number of websites on it, and even sell some of your hosting space to others. This is one of the most effective methods for making money online. They will take care of all your customers’ hosting needs, so you do not need to fret about hosting-related matters.