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

Introduction to Web API Recap

Uploaded by

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

Introduction to Web API Recap

Uploaded by

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

Introduction to Web API

ASP.NET Core Web API is a component (part) of ASP.NET Core, which is used create
HTTP-based RESTful services (also known as HTTP services) that can be consumed
(invoked) by wide range of client applications such as single-page web applications, mobile
applications etc.

Asp.Net Core:

● Asp.Net Core MVC


● Asp.Net Core Web API
● Asp.Net Core Blazor
● Asp.Net Core Razor Pages

RESTful / Web API Services

RESTful services (Representational State Transfer) is an architecture style that defines to


create HTTP services that receives HTTP GET, POST, PUT, DELETE requests; perform
CRUD operations on the appropriate data source; and returns JSON / XML data as
response to the client.

Web API Controllers

Should be either or both:

● The class name should be suffixed with "Controller". Eg: ProductsController


● The [ApiController] attribute is applied to the same class or to its base class.

Controller

[ApiController]
class ClassNameController
{
//action methods here
}

Optional:

● Is a public class.
● Inherited from Microsoft.AspNetCore.Mvc.ControllerBase.

Introduction to Swagger

Swagger is a set of open-source tools that help developers to generate interactive UI to


document, test RESTful services.

Swagger is a set of tools to implement Open API.

1. Swasbuckle.AspNetCore

Framework that makes it easy to use swagger in asp.net core.

2. Swagger

Set of tools to generate UI to document & test RESTful services.

3. Open API

Specification that defines how to write API specifications in JSON).

API Versions

API Versioning is the practice of transparently managing changes to your API, where the
client requests a specific version of API; and the server executes the same version of the
API code.

Content Negotiation

Content negotiation is the process of selecting the appropriate format or language of the
content to be exchanged between the client (browser) and Web API.
Overview of Minimal API

- It is a Microsoft's API that is used to create HTTP services (or HTTP APIs) with minimal
dependencies on packages.

- Alternative to Web API Controllers. Mainly used to create HTTP services or Microservices.

REST API (Representational State Transfer)

MVC Controller (Microsoft.AspNetCore.Mvc.Controller)

● Full support for model binding and model validation.


● Full support for views.
● Full support for filters & filter pipeline.

API Controller (Microsoft.AspNetCore.Mvc.ApiControllerAttribute)

● Full support for model binding and model validation.


● No support for views.
● Full support for filters & filter pipeline.

Minimal API (IApplicationBuilder.Map* Methods)

● Limited support for custom model binding and custom model validation (needs to
improve).
● No support for views.
● No support for filters & filter pipeline; but supports "Endpoint Filters" alternatively.

Routing in Minimal API

1. MapGet()

Creates an endpoint that receives HTTP GET request.

app.MapGet("/route", async (HttpContext context) => {


await context.Response.WriteAsync("your response");
});

2. MapPost()

Creates an endpoint that receives HTTP DELETE request.


app.MapDelete("/route", async (HttpContext context) => {
await context.Response.WriteAsync("your response");
});

3. MapPut()

Creates an endpoint that receives HTTP PUT request.

app.MapPut("/route", async (HttpContext context) => {


await context.Response.WriteAsync("your response");
});

4. MapDelete()

Creates an endpoint that receives HTTP DELETE request.

app.MapDelete("/route", async (HttpContext context) => {


await context.Response.WriteAsync("your response");
});

Route Parameters in Minimal API

Route parameters can be created as you were creating them in UseEndpoints() or in MVC
controllers.

app.MapGet("/route/{parameter}", async (HttpContext context) => {


await context.Response.WriteAsync("your response");
});

Route Constraints in Minimal API

Route constraints can be used as you were using them in UseEndpoints() or in MVC
controllers.

app.MapGet("/route/{parameter:constraint}", async (HttpContext context) => {


await context.Response.WriteAsync("your response");
});

Eg: int, bool, datetime, decimal, double, float, guid, long, Minlength, maxlength, length, min,
max, range, alpha, regex, required

Map Groups in Minimal API

A map group (or route group) is a set of endpoints with a common prefix.

A map group is a collection of endpoints created with Map* methods such as MapGet(),
MapPost() etc.

MapGet()

Creates an endpoint that receives HTTP GET request.


var mapGroup = app.MapGroup("/route-prefix");

mapGroup.MapGet(…);
mapGroup.MapPost(..);

IResult

The Microsoft.AspNetCore.Http.IResult is the base interface that is implemented by different


result types such as Ok, Json, BadRequest etc., which can be returned by endpoints in
minimal API.

1. Results.Ok( )
2. Results.Json( )
3. Results.Text( )
4. Results.File( )
5. Results.BadRequest( )
6. Results.NotFound( )
7. Results.Unauthorized( )
8. Results.ValidationProblem( )

IResult Implementations

1. Results.Ok

Response Content-type: application/json [or] text/plain

Response Status Code: 200

return Results.Ok(response_object); //can be a string or model

2. Results.Json

Response Content-type: application/json

Response Status Code: 200

return Results.Json(response_object); //should be a model

3. Results.Text

Response Content-type: text/plain

Response Status Code: 200

return Results.Text(response_string); //should be a string

4. Results.File

Response Content-type: application/octet-stream


Response Status Code: 200

return Results.File(stream_object); //should be 'System.IO.Stream'


type

5. Results.BadRequest

Response Content-type: N/A

Response Status Code: 400

return Results.BadRequest(response_object); //can be a string or


model

6. Results.NotFound

Response Content-type: N/A

Response Status Code: 404

return Results.NotFound(response_object); //can be a string or model

7. Results.Unauthorized

Response Content-type: N/A

Response Status Code: 401

return Results.Unauthorized(response_object); //can be a string or


model

8. Results.ValidationProblem

Response Content-type: application/json

Response Status Code: 400

return Results.ValidationProblem(response_object); //automatically


creates JSON with validation errors

Endpoint Filter

EndPoint Filters execute much like 'action filters' i.e., 'before' and 'after' the execution of
minimal API endpoint.

They are mainly used to validate parameters of the endpoint.


Creating an Endpoint Filter

Endpoint filters can be registered by providing a Delegate that takes a


EndpointFilterInvocationContext and returns a EndpointFilterDelegate.

app.MapGet("/route", () => {
//your endpoint code here
})
.AddEndpointFilter(async (context, next) => {
//before logic
var result = await next(context); //calls subsequent filter or endpoint

//after logic
return result;
});

IEndpointFilter

Creating an Endpoint Filter by implementing IEndpointFilter interface

The InvokeAsync() method takes a EndpointFilterInvocationContext and returns a


EndpointFilterDelegate.

class CustomEndpointFilter : IEndpointFilter


{
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context,
EndpointFilterDelegate next)
{
//before logic
var result = await next(context); //calls subsequent filter or endpoint

//after logic
return result;
}
}

You might also like