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

Creating The Api and Returning Resources Slides PDF

This document discusses various aspects of creating and returning resources from an API, including: 1. It clarifies the Model-View-Controller pattern and how it is commonly used to build client-facing web applications near the presentation layer. 2. It covers attribute-based routing in ASP.NET Core, how routing matches requests to controller actions, and common routing attributes like HttpGet, HttpPost, etc. 3. It discusses how APIs can return different models than those used internally, the importance of status codes, content negotiation to select the best response format, and getting files from the API.

Uploaded by

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

Creating The Api and Returning Resources Slides PDF

This document discusses various aspects of creating and returning resources from an API, including: 1. It clarifies the Model-View-Controller pattern and how it is commonly used to build client-facing web applications near the presentation layer. 2. It covers attribute-based routing in ASP.NET Core, how routing matches requests to controller actions, and common routing attributes like HttpGet, HttpPost, etc. 3. It discusses how APIs can return different models than those used internally, the importance of status codes, content negotiation to select the best response format, and getting files from the API.

Uploaded by

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

Creating an API and Returning

Resources

Kevin Dockx
Architect

@KevinDockx https://www.kevindockx.com
Coming Up Clarifying the MVC pattern
Returning resources
Interacting with an API
Content negotiation
Getting a file
Model-View-Controller
An architectural software pattern for implementing user interfaces
Very common pattern
Clarifying the - Exists in many languages, supported by
many frameworks
MVC Pattern - Used to build client-facing ASP.NET Core
web applications
Model-View-Controller
An architectural software pattern for implementing user interfaces
Clarifying the MVC Pattern

Loose coupling

Separation of concerns

Testability

Reusability
Not a full system and/or application
Clarifying the architecture pattern!
MVC Pattern - Typically lives near the presentation layer
Clarifying the MVC Pattern

Model

View Controller
Clarifying the MVC Pattern

Consumer of the API

Model
Resource representation
(often JSON)
Demo

Registering API services on the container


Demo

Returning resources (part 1)


Routing
Routing matches a request URI to an action on a controller
app.UseRouting()
- Marks the position in the middleware
pipeline where a routing decision
Learning About is made

Routing app.UseEndpoints()
- Marks the position in the middleware
pipeline where the selected endpoint
is executed
app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints => {
// map endpoints });

Learning About Routing


Middleware that runs in between selecting the endpoint and executing the selected endpoint
can be injected
app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints => {
// map endpoints });

Learning About Routing


Middleware that runs in between selecting the endpoint and executing the selected endpoint
can be injected
app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints => {
endpoints.MapControllers();});

Attribute-based Routing
No conventions are applied
This is the preferred approach for APIs
app.UseAuthorization();

app.MapControllers();

Attribute-based Routing
Shortcut: call MapControllers on the WebApplication object directly
- Default in .NET 6
- Mixes request pipeline setup with route management
Use attributes at controller and action level:
Attribute-based [Route], [HttpGet], …

Routing Combined with a URI template, requests are


matched to controller actions
Attribute-based Routing
HTTP Method Attribute Level Sample URI
/api/cities
GET HttpGet Action
/api/cities/1
POST HttpPost Action /api/cities

PUT HttpPut Action /api/cities/1

PATCH HttpPatch Action /api/cities/1

DELETE HttpDelete Action /api/cities/1

--- Route Controller ---


For all common HTTP methods, a matching
Attribute-based attribute exists
Routing - [HttpGet], [HttpPost], [HttpPatch], …
Attribute-based Routing
HTTP Method Attribute Level Sample URI
/api/cities
GET HttpGet Action
/api/cities/1
POST HttpPost Action /api/cities

PUT HttpPut Action /api/cities/1

PATCH HttpPatch Action /api/cities/1

DELETE HttpDelete Action /api/cities/1

--- Route Controller ---


[Route] doesn’t map to an HTTP method
Attribute-based - Use it at controller level to provide a
Routing template that will prefix all templates defined
at action level
Attribute-based Routing
HTTP Method Attribute Level Sample URI
/api/cities
GET HttpGet Action
/api/cities/1
POST HttpPost Action /api/cities

PUT HttpPut Action /api/cities/1

PATCH HttpPatch Action /api/cities/1

DELETE HttpDelete Action /api/cities/1

--- Route Controller ---


Demo

Returning resources (part 2)


Demo

Using Postman
Demo

Improving the architecture with


model classes
The outer facing model (DTO) is different from
the entity model (which maps to your
One Application, datastore)
Different Models - Will become apparent when we introduce
Entity Framework Core
public class CityDto
{
public int NumberOfPointsOfInterest { get; set; }
}

public class PersonDto


{
public string FullName { get; set; }
}

One Application, Different Models


The outer facing model is different from the entity model
- E.g.: calculated fields on the outer facing model
public class CityDto
{
public int NumberOfPointsOfInterest { get; set; }
}

public class PersonDto


{
public string FullName { get; set; }
}

One Application, Different Models


The outer facing model is different from the entity model
- E.g.: calculated fields on the outer facing model
public class CityDto
{
public int NumberOfPointsOfInterest { get; set; }
}

public class PersonDto


{
public string FullName { get; set; }
}

One Application, Different Models


The outer facing model is different from the entity model
- E.g.: calculated fields on the outer facing model
// Entity
public class City
{
public int Id { get; set; }
}

public class CityForCreationDto


{
// no identifier
}

One Application, Different Models


The outer facing model is different from the entity model
- E.g.: identifiers on the entity model
// Entity
public class City
{
public int Id { get; set; }
}

public class CityForCreationDto


{
// no identifier
}

One Application, Different Models


The outer facing model is different from the entity model
- E.g.: identifiers on the entity model
Status codes tell the consumer of the API
The Importance - Whether the request worked out as
expected
of Status Codes
- What is responsible for a failed request
Common mistakes:
- Don’t send back a 200 Ok when something’s
The Importance wrong
of Status Codes - Don’t send back a 500 Internal Server Error
when the client makes a mistake
- …
The Importance of Status Codes

Level 100
Informational
The Importance of Status Codes

Level 200 Level 300


Success Redirection

200 – OK

201 – Created

204 – No Content
The Importance of Status Codes

Level 200 Level 400 Level 500


Success Client mistake Server mistake

200 – OK 400 – Bad Request 500 – Internal


Server Error
201 – Created 401 – Unauthorized

204 – No Content 403- Forbidden

404 – Not Found

409 - Conflict
Demo

Returning correct status codes


Demo

Returning child resources


Content Negotiation
The process of selecting the best representation for a given response
when there are multiple representations available
The media type(s) is/are passed through via
Formatters and the Accept header of the request
Content - application/json
- application/xml
Negotiation - …
Formatters and Content Negotiation

Output formatter Input formatter


Deals with output Deals with input
Media type: Accept header Media type: Content-Type header
Formatters and
Support is implemented by ObjectResult
Content - Action result methods derive from it
Negotiation
Demo

Formatters and content negotiation


Demo

Getting a file
Summary Model-View-Controller
- Model: application data logic
- View: display data
- Controller: interaction between View
and Model
The pattern improves reuse and testability
Summary
Routing matches a request URI to an action
on a controller
- Attribute-based routing is advised for APIs
Summary
Content negotiation is the process of
selecting the best representation for a
given response when there are multiple
representations available
Summary
Use the File method on ControllerBase
to return files
- Think about setting the correct
media type
Up Next:
Manipulating Resources and Validating Input

You might also like