You are on page 1of 46

Course Overview

Course Overview
[Autogenerated] Hi, everyone. My name is Kevin. Welcome to my course Implementing
and fast stressful concerns at a speed of net core tree. I'm a Microsoft M v P m
freelance solution architect currently focused on security and building a P I. In
this course, we're going to learn how to implement advanced stressful concerns with
air speed up that tree. Some of these concerns might not be so obvious at first,
but implementing them will lead to a better, more evolved will a p I so off the
major topics that we will cover includes Beijing sorting and data shaping.
Implementing Hato s support or hyper media as the engine of application State
advanced counter negotiation scenarios to improve the reliability off you're a p I
and cashing and concurrency by the end of this course will know all about arrest
constraints and you'll end up with a level tree rest ful FBI, which is the highest
possible level of maturity before beginning the course. You should be familiar with
the SP dot net core and C sharp. I hope you'll join me on this journey to learn how
to improve your weapon. FBI with implementing viral stressful concerns with the
hospital that court recourse at plural side

Supporting Paging for Collection Resources


Coming Up
[Autogenerated] hi there and welcome to the scores. Implementing advance stressful
concerns with a speed of net core tree I'm given and I'll guide Truitt. We'll start
this module by positioning the scores and having a look at the courts.
Prerequisites. After that, we'll look into the tooling and framework versions were
going to use after that. Well, recapitulate what rest ISS, including which parts of
it are covered in this course. Then we'll dive into Beijing. AP ice typically have
a need for paging on their collection resources. To avoid performance implications,
we learn how to accept paging parameters and how to ensure that these get sent
through to the underlying data store. While doing so, we'll learn about a very
important principle deferred execution When designing a page in Asian solution.
It's important to keep rest ful principles in mind, especially when thinking about
how we should return medal later. Well, notice this quite quickly when we cover
pagination metal data. If you happen to have any questions, the best place to pose
them is on the discussion tap on the course page. I checked this regularly and like
that, the questions and answers can help other people out to swell for very short
questions that require a quick answer. You can contact me on Twitter or just follow
me. If you want to know about my upcoming courses usual group events, or are
interested in the technology I'm interested in. I mainly tweet regarding a spittle
net, core security and AP eyes. These days. Let's have a look at what you can
expect of this course and what the prerequisites are.

Positioning this Course


[Autogenerated] This is an intermediate course on building rest ful. A P I rest is
definitely the focus point of it. Large off C sharp is required, obviously, and
some knowledge of a hospital netcord will come in handy as well, because that's
what we'll use to build the FBI. If you haven't worked at a speed of net core
before, you might want to have a look at sculpts, a Speedo kinetic or fundamental
scores. But there's more. You might have noticed that this course tackles advanced
rest ful concerns. You also might have noticed that I have another course building
rest ful, a p I with a hospital net core tree. This course builds on that one.
That's because rest is a really big subject. Fitting all of it into one course
would have made the course very long. That's why it split up. First course covered
the basics. This course covers advanced concerns. That doesn't mean you need to
follow both courses. If you already know a thing or two about rest, you can jump
right in or just mix and match to your liking. But if rest is a new concept for
you, it's probably a good idea to follow the beginner course. First. Let's look at
the tooling options we have

Tooling
[Autogenerated] will use Visual Studio 2019 for the team was in discourse to use
dot net core tree you need version 16 point tree or better if you haven't got a
name is D analyzed since you can now look to free Community Edition. But that
doesn't mean that you need visuals to your 2019 to follow along any I d. That
supports free work, version and or application type you're working with can be used
depending on your needs. That might be visual studio coat, visual studio for Mac or
other ideas like jetbrains Rider or Sublime. However, Visual Studio 2019 does offer
the best stooling at the moment off. Recording our co two targets Don't net core
tree. If you haven't got that yet, you'll have to dilute it. You can find it at the
______ on screen. Simply download and install the full 3.0 as decay and you're good
to go. That's it for the i D and dot net core versions. What will you Some other
tools as well to create requests to our FBI and to see the response messages will
use postman Postman is free tool you can use to amongst other things, create and
send http requests and inspector responses bundled together with the exercise files
are all http request will send in this course So you can just import having postman
and use them. Save you a bunch of typing. You'll need a browser of choice as well.
And that's about all that's needed to get started. As usual, the exercise files can
be found. Fire the exercises. Stop on the course page The Post. My requests are
gonna file in the root folder off the day. Most off this marshal, it's named
Implementing Advance Stressful Concerns. Don't Postman Collection as an alternate
if you can also get the start of solution and finished sample from I get up, The
postman request can be found in the root folder here. A swell. Let's have a look at
the _____ application we're going to use

Demo - Introducing the Demo Application


[Autogenerated] we're not starting from scratch in this course. We're starting from
the Finnish solution off my building. Arrest fel a p I with the air speed Internet
Court recourse! Let's have a look at it. Our FBI exposes alters fire the orders
Controller or alter collections controller for the collection of alters and courses
fired, of course, is control the back end store Isn't f core database containing
these Alderton courses? These are accessible via the course library context from
our controllers. We access these true the course Ivory depository. If you look at
the program class, we see that whenever the application starts the databases the
leader then seated again like that we can always start with a clean slate. Quite
few things have already been implemented in this solution. All, http, methods like
get hat boast options delete and for courses put am patch have been implemented.
Input validation is in place a swell at least for courses bowed by using data,
annotations and custom attributes. What's exposed by the actions on the controllers
and accept that as input are de dios? That means we need to map between the
entities and the de Dios. And for that all democracies used. You can find the altar
mapper profiles in the Profiles folder. Next to that, if you look at the
implementation of get Older Son or depository, we can see that altar skim already
be filled with and search. So all in all this is already a pretty decent maybe I
with quite a bit of functionality. But some pieces of functionality are missing,
like Beijing and sorting. And on top of that, this AP I isn't exactly rest ful yet.
Why that's the case and how we can fix that is what we will learn in the next two
hours. The first few models off this course tackle, paging, sorting and data
shaping. These are functionality is a lot of AP eyes need. But there's more to a P
ice, and especially to rest then just additional functional use cases. The cost. US
also covers Hato US advanced counter negotiation, cashing and dealing with computer
unsee. Those things have to do with the rest constraints. They are often overlooked
or wrongly implemented. We'll cover both functional use cases, and I've deeper into
those constraints. But to understand some of the specifics we need to keep in mind
when Beijing sorting and data shaping it is important to already know a thing or
two about these constraints. That's why I will continue with a short 101 on what
rest ISS.

Recapitulating REST
[Autogenerated] rest is an architectural style constrained by a set off
constraints. These constraints can be seen as design decisions. Each of those can
have vote positive and negative impacts. So for these constraints, the benefits are
considered to outweigh the disadvantages. There's quite a few constraints to a dear
to you can see them on screen. All of these have been explained in my building
arrest for a P I with the s p dot net court recourse. But not all of them have been
implemented yet. What we will implement in this court is related to two off these
constraints. Do you any form, interface, constraint and the casual constraint?
Let's have a look at those uniform interface constrained states that the A P I and
a P I consumers share one single technical interface or contract. As we're
typically working with the http protocol is, interface should be seen as a
combination off resource. Your eyes. In other words, where can you find your
resources? Http methods, In other words, how can we interact with them? For
example, true get or both etcetera and http media types like Application Jason
Application and XML that are reflected in request and responsibilities. This is
also called the contract Between Client and A P I and the thigh Third base is the
more reliable and evolve herbal client, and a P I become that's pretty. Three parts
on the slide in this course will dive deeper into the last part of the contract
payload defined by media types. We will learn that application. Jason doesn't
guarantee a tight contract which isn't that good in regard to reliability and
evolve ability. We will improve on that with advanced quantum negotiation and
vendor specific media types. Toe get to such a well designed technical interface
between client and FBI. Do you reform interface constraint is divided into four sub
constraints. First up constrained is the identification of resources of
constraints. It states that individual resources are identified in requests using
your eyes. Resources themselves are conceptually separate from the representations
that are returned to the client in our day. Most who will work with altars and
courses on all the resorts could be found that a B i forward slash alters forward
slash your i d. But that resource is conceptually different from the presentation
off that resort that's returned in the response to representation could be Jason in
most cases, but it can also be expelled, and other types were also possible. This
is mostly related to the first part of the contract. Seconds up constraint is the
manipulation off resources through the presentation Subject Street. This one states
that when a client holes or the presentation of a resource, for example, Jason or
XML, including any possible metal later it must have enough information to mollify
or the lead to resort on the server, provided it has permission to do so that is
thus related to the payload part of the contract. The third sub constraint is the
self descriptive message constraint. This one states that each message must include
in love information to describe how to process the message. When a consumer
requests data from an A p I, we send a request message, and when he gets back data,
that's a response message, and such a message is headed on a body. If requests body
contains cheese from the presentation of resource, the message must pacify that
fact in its headers. By including the media type like application, Jason like that,
the correct parts that can be invoked to process the request body and it can be
serialized into the correct class. Same for the other way around. This constraint
do is related to the payload part of the contract. All these constraints have
already been implemented in the devil. The last one hasn't been, and that's hate
us. It means hyper media as the engine of application state dis constraint balls
down to creating a self documenting A P I. And the documentation can then be used
by client applications to provide functionality to the user. It's not an easy
constraint to understand it's mainly related to the payload part of the contract.
But as it describes the AP, I it is in a way also related to each other part of the
contract. There's two full modules dedicated to it in this course. It offers some
really interesting possibilities, like operating a business rule at a pea eye
level, which the Kyle can learn about without having to update your clients
version. I think it adds a lot of value to an A B I. Now, looking at this slide, it
seems like there's a lot of attention going onto the payload represented by media
types like application chase. There's a quote by really feeling, and that's the guy
who invented the term rest. And who described the architectural style that hidden
stores. Why, that's the case. It states that arrest a p. I should spend almost all
of its descriptive effort in defining the media types used for representing
resources. Well, that's interesting. If application Jason would be the only media
tie abused, there wouldn't go a lot of effort into describing it right. That's
because arrest fel a P I and regular Web A P I. R. Two different beasts. We will
learn a lot about his media types how to create him, why they are so important
during the course onto the next constraint. The casual constraint this one states
that each response message must explicitly state if it can be cashed or not. It's
quite easy to a deer to simply ensure each response states that it cannot be cashed
and we're compliant. But where's the fun in that? Most applications require
cashing, and that's exactly what we will implement In this course like this. We can
eliminate some client server interaction and at the same time prevent clients from
re using out of date data. Http. Cash, sometimes called the old the grail of
cashing with e tax is the typical standards used in arrest architectural system. So
they should give you an idea what this course is about. But there's more. We're
kind of getting ahead of ourselves next to a dearing. To these constraints, AP eyes
often need additional functionality. Think about paging, sortie and data shaping.
Let's continue with implementing paging support for our A B I.

Paging through Collection Resources


[Autogenerated] most AP eyes just like ours, exposed collection resources, altars
and courses in our case, and these collections can grow quite large. It's
considered best practice to always implement paging on each resource collection, or
at least on those resources that can also be created. This is to avoid unintended
negative effects on performance when resort collections grow. Not having paging on
a list off, then all those might be okay. But if you're a P, I allows creating
alters like ours does. This list can grow, and we don't want to end up with
accidentally returning thousands of alters in one response, as that will definitely
have an adverse effect on performance imagination. Parameters are typically passed
through fire Macquarie Street. That means that these are not resources in their own
right. They are parameters that manipulate resource collections. As far as paging
is concerned, consumers should be able to choose the page number and page size, but
that beach size can cause problems as well. If you don't limit this, a consumer can
pass through 100,000 as a page eyes, which will still definitely cost performance
issues. So the pay Chuy's itself should be checked against a specific value to see
if it isn't too large. If no Beijing parameters are provided, we should only turn
the first page by default. So we are manipulating a collection resource for things
like paging toe work correctly and have a positive impact on performance, or at
least the best possible impact we need to ensure that this goes all the way through
to our data store. For example, if we have thousands of orders in our database,
every first return all those alters from the depository to the controller and then
page them, we still fetch way too much data from the database and that still has a
negative effect on performance. We'll have to keep that in the back of our heads
when implementing this. Let's have a look at a table.

Demo - Paging through Collection Resources


[Autogenerated] in this day more. We're going to implement paging functionality as
an example will do this on our orders collection. We're going to get alters action
on the altars. Controller here will want to accept two additional parameters from
the query, string page number and bait size. I say additional because if we look at
the action, signature received already has a parameter alters resource parameters
from query Attribute tells us this is coming from the query string. Let's have a
look at that. It contains a main category. Property used for filtering and a search
quite a property used for surgery. These are bound from the main category query,
string value and search credit credit string value, respectively. So here we can
add a page number and page size page number signifies the page we want to get, and
page size signifies the maximum amount of items on the page. It's important to give
these parameters default values like that. We can ensure that if a consumer doesn't
passing values for these parameters, the default will be used. Let's say will
default to page wrong with the size of them. There's one more thing we have to
think about a maximum bait size. We've got a default here now then, but a consumer,
often a p I can still input 1000 and that will be accepted. That shouldn't be the
case, as that would have a negative impact on performance. So we'll have a constant
that defines the Maxine Page ice say, 20. I tend to have a maximum page size for
each resource collection instead of one general maximum page eyes for all resource
collections. This is because you might want to let consumers of the A P I get a
maximum of 10 alders per page, but maybe 20 courses per page when implementing
paging on that collection. Now we have a max pay Chuy's. We should take that into
account when setting the bait size. We need to check if the page size isn't higher
than the maximum page eyes. And if it is, we set the page size to the maximum page
eyes and we that we've got our parameters back to our action. We see that these
parameters are passed to the get alter Smell it on the depository. Let's have a
look at that. As you can see, this curently implements filtering and searching. We
want to add Beijing functionality to this as mentioned ride before the day. Bo, we
need to make sure that our page nation is done a database level and not after the
records have been fetched. This can be done thanks to deferred execution. That
principle means that the query variable itself never holds the credit results and
only stores the credit commands. Execution off the credit is deferred until the
credit valuable is iterated over. So deferred execution means that Kredi execution
occurred sometime after the credit is constructed. We can get this behavior by
working with Aiko Variable implementing collections. I credible of tea allows us to
execute a _______ against a specific data source, and while building upon it, it
creates an expression tree that's still squarely commands. But the query itself
isn't actually sent to the data store until it oration happens. Integration can
happen in different ways. Want is by using. I quit well in the loop. Another way is
by calling something like to list too airy or two dictionary on it because that
means converting the expression tree to an actual list of items and yet not a way
is by calling Singleton crazies. Singleton qualities are critics like average,
gowned, and first, because to get to the count or the first item of an incredible
the list has to be iterated over. But as long as we avoid that, we can build our
credit, for example, by adding take and skip statements to it. For Beijing, doing
so ensures the quality is only executed. After those statements have been added, we
can already see that principle at work. The collection we start from is an eye
credible of altar. Potentially, a filter and search query are applied. I eat, We
are building equity, and the credit is only sent to the database at the end when
the do List statement is reached. So what we can do is apply Beijing to this
collection before calling to list. It's important to add a paging functionality
last because we want to page on the filter than search collection. If we had paging
first, the wear and other extension methods will execute on the small set of data
instead of on all the data, and that would lead to incorrect results. What do you
want to do? Is first skipping amount of alters the page size times, the requested
page number minus one that will ensure that, for example, if Beach Do is requested,
the amount of items on page one will be skipped. And then we take two curently
requested page eyes. One more thing. If we scroll up a bit, we see an if statement
that ensures that all those already turned, if main category in search, query or
empty. That's great if you only have those two pieces of functionality implemented.
But in our case, we want to get rid of that. We learned we want to apply paging no
matter what, and that includes paging when no filter or search query has been
impotent. So let's get rid of this statement. All right, let's give this a try. We
didn't postman on the left. You can see a collection of requests. These are the
requests were going to use throughout the course, and these are also requests that
are distributed together with this course. If you haven't imported such a
collection before, simply click import and director collection file that's
distributed together with the course do this window. The second thing to think
about is your eye. These requests assumed that the port we're running on its five
fund zero for four. But if you're starting from another solution or you're just
implementing this on your own solution, make sure that the port number matches. All
right, let's send this regressed. We didn't vase in any parameters, so we should
see a page set with the default restrictions. The first page off that alters. And
that is indeed the case. Before we send another request, let's have a quick look at
the console. We know where we can see the actual credit that was sent to the
database. Here we can see that paging was applied. We see that the credit contains
an offset statement. The results are offset it by the first parameter, after which
a number of rows matching the second parameter are fetched. That's Beijing at work,
so this means we are not first loading alters the memory. Instead, only the amount
requested is fetched. Now that's bossing some paging parameters. Say we want the
first page of data with a maximum of five alters per page. Repose those parameters
in true to your eye, let's click sent and there we go. Only five holders and what
would happen if he passed through a page? Guys off 100? That's definitely more than
the maximum page eyes were allowing. Let's click, send and there we go. On Lee. The
maximum amount of falters have been returned. Now let's try getting the second page
for that. We change the page number do, too. Let's get sent. And there we go alters
six through 10 who are more tests? What would happen if he passed through an empty
value for page, size or page number? That's good accent. We get back an adult in
the 400 level exactly as expected, as the client made a mistake. But something
seems to be missing. If we're paging through data, especially with defaults in
place, we should return some meta data related to the resource collection like
that. The consumer can get essential information on the collection resource like
curing page or total amount of pages together with the response. Let's do that next

Returning Pagination Metadata


[Autogenerated] Let's think about what would be useful for the consumer of the A P
I to know about Paige Set of data. At the very least, we should include your eyes
to request the previous and next pages so the consumer doesn't have to construct.
It was himself. Additional information is often included. A swell, the total count
or the total amount of pages, page number and or page size. How do we include his
data in the response than what's often? Don't and you probably already encountered
this. If you've worked with third party A PPI, eyes like Facebook's is that paging
information is included in the response body itself, often with a meta attack or a
Beijing Info attack. You can see an example of that on screen, but this isn't
completely correct. If a consumer of the A P I requests a page of altars with the
application Jason Media types value for the except enter the AP, I should return
adjacent presentation off the resource so off a set of orders. But this isn't just
an area of orders. It's an envelope that includes value, which contains the area of
orders and the med aerator property which contains the paging matter later. So this
doesn't really match requested media type. This is something else. It's a different
media type. So next we're returning the wrong the presentation. No response will
have a content type heather with value application. Jason, which doesn't match the
content of the response. In other words, we also don't tell the consumer how to
process it to consumer doesn't know how to interpret the response. Judging from the
counting type as the content type, it's not strict enough. So when requesting
application, Jason Beijing information isn't part of the disorder presentation.
It's metal later related to that resource and metta later. That's something that's
putting a response center the consumer. Can them parts that Heather to get that
information so we should create a custom imagination header like Expedia Nation to
be completely correct. Well, I currently call metadata is actually a combination of
two different things. The links to the previous and next pages tell the consumer of
the A P I how to navigate through the A B I. It tells it how to go to the previous
or next page, and the rest of the information Black ____, you're on page size is
actual metal. Later on the beach Collection resort that's in the response body.
Once we learn about HATO us, we'll learn about this in detail and split us up some
more. And we'll also learn a bit more about these media types and how to use a
customer. But for now, this is sufficient. How do we do that, then? Well, we could
just create an additional reports story method that returns the meta later. But I'm
not a big fan of that page. Data and related meta data feel like they belong
together. So in the next two day, most will do two things. We're going to create a
new class page list, which holds to curing page. Total pages has previous and us
next fields. We don't have to do that, but by doing so, we can really use that
class for other collection resources. Like the courses as we know it's best
practice to page all collection resources by default to avoid an unintended
negative impact on performers. This class will make it a lot easier once we have
that we have all the information required to create a meta later, so that's what
we'll do in the day. More after that, let's continue

Demo - Improving Reuse with a PagedList<T> Class


[Autogenerated] in this demo will create a page list glass that'll handle Page
Nation for us and will serve as a container for the Cure and Paige. Total Pages has
previous and has next properties. Let's add a new class to the help of folder based
list. Let's name it page list. We make this a page list off D, and we just want to
add a little bit of functionality to a list off the swill dr from that list off the
So let's think about what we need in this class. We'll need to know ____, you're on
page long and the total amount of pages. So let's add two properties. For that.
We'll give him a private center so they can't be manipulated from outside of this
class. Allowing that could lead to invalid values off those properties. Two other
properties that can be useful in the metal later is the page size and the total
amount of items. So he had those as well, Then people want to know if there's a
previous page or the next page. Those are properties we can calculate from the cure
in page and Total Page properties has previous should be true if cured and pages
larger, don't want and as next should be true. If you're on page is smaller than
the total amount of pages, then we'll need a constructor for this will accept a
list of tea items account the total amount of items on the list, the page number
and Bay Jai's. Those are the values we passing from that. We can already set three
of our properties. The total count page size and Nick you're on page total count.
That's the count. It's Boston base. Eyes is the page. Ice pasta and curing page is
simply the page number. The total amount of pages can be calculated with matter
ceiling. We divide count by the page eyes and call mental ceiling on it mattered.
Ceiling returns the smallest, indeed real value that is greater than or equal to
the input. So if you have 101 records to the page, eyes off them. This will return
11 because result imminent and assign it to the total pages property. Lastly, we
call at Rage. Passing in the impotent items At range is a method only stuff T,
which are paged list derived from so this adds all the items to the list. We won't
directly call this constructor. Instead, we had a static med it create that will
create this page list for us that allows us to call page list of Create passing and
I credible, which is exactly what we get after applying the order by clause in our
report story. So all costs and calculations required phenomenon in the create
method rather than having to do that before creating the page. Dist. Static Method
Returns page list off D It accepts an equitable of T the page number and a page
size. That's all the information we have in our depository method. To be ableto
call the constructor. From this method, we need to calculate the total amount of
items and the correct paged items. To get the count we call count on the source to
get the actual page with the exact same calculations as we did in the depository.
In the previous table, we skip page number minus one dime _____ size and we take
the page size. Then we go to list on this because we need these items when using
this would entity framework or to list will result in the credit being executed,
and this is okay because, as we learned in the previous Daymo, Beijing is the last
thing. You want to do it on my credible before executing the credit. Lastly, we
create a page list off the passing in the items count, page number and page size,
and that's what we returned. That's all we need to do in this class. Now let's use
this. That's open the repository contract first instead of returning and i
innumerable of altar, we now want to return a page list that's defined. In course,
I read of a P I don't helpers. So that's Addie, using safe in my pressing enter
onto the implementation. Here, too, we change the method signature so it returns a
page list of altar. So here, too, we have to import that name space. There we go.
Let's cool down a bit. The skip and take statements are taken care off by our page
list so we no longer need them here. That means we can call page list off, create
passing through the collection, the page number and the baby's eyes. There we go.
Let's give this a try. Let's execute that request from the previous demo again for
fetching Page two with Paige Eyes of five. And there we go. This works is expected.
So far, so good. We now have a reusable page list, and on it are all the properties
we need to create a metal later from, Let's do that in the next table.

Demo - Returning Pagination Metadata


[Autogenerated] in this day more. We'll learn how he can be turned pagination
metal. Later, we'll return the data in a custom pagination header, and there's a
few pieces will have to build to allow for that before we can return this matter.
Data. We need a way to generate it. Older from Rebo in or get Office Med. It is now
a paged list. So far, so good. What do you want to do is generate your eyes to the
previous and next page if those exist. If you first with the oldest people. Net Web
A P I. You know, there used to be a class that would help with that. Do you? Well,
helper comparable class exists in their speed of net core. You were all helper.
Which implements are you? Well, helper? It's available on each based controller to
DUl property, and that's your little helper has a method link that generates an
absolute your eye. Using the route name and a set of values, we want to refer to
the get alters action. So let's give the route the name First. We do that by
setting the name property to the name we want get altar for example, then let's
create our legs. We're gonna do that in a private jet that's name it. Create alters
resorts you would I it, except on altars. Resource parameters object as we need
that to generate your eyes. And it should accept an intimidation so we can pass in
whether we want to generate previous or next page link. So that enumeration
resource your eye type doesn't exist yet that's added to the helpers folder. We'll
have to values to it. Previous page and next page we will revisit is in admiration
later, all in the course when another type will be at it. But more on that later
back to the controller. We can now implement this method. For that. We can add a
switch statement on this tie parameter to create a link to the previous page. We
use the link method, he bossing the route name and a set of values. These values
are the query string parameters, beach number and Bates eyes. So we passing a new
object and set the page. Number two. The curently requested page minus one because
we want to link to the previous page. Beach size stays the same important is that
we also return any additional fields that may have been impotent, like the main
category in search credit. If it only include these are previous and next page
links will not refer to the correct set of data likewise for you, right to the next
page. But this time we add one to the page number, and as a default, we return a
cure in page Link. All right, now we can use this method. Let's crawl up to the
ghetto alters action. First thing to do is check if there is a previous page. We
can do that by checking the has previous bullion on the page list our orders from
liberalised if there is one, be generated by calling into the create alter freeze
or see where I met it, passing all the resort parameters and previous page as
resource your eye type. Otherwise, we said it, too. No, and we do something
likewise for the next page link. Then let's create at meta data. For that, we
instance she ate new object and we pass in the values we get from the page list.
Total count page size during page and total pages. We also passed through the
previous page link and next page link we just generated. You can see that previous
page link and next page link our grayed out. That's because if we don't pass
through a specific name for a field, the name off the valuable issues and in our
case, previous page link as field name equals our previous page link valuable name
so we can get rid of that. There we go, the last part of the story. It's adding
this as a custom header through the response. For that we call into the at methods
off the headers collection on the response, every passing, the key for the header.
Ex pagination, second parameter. We need to pass through its value. He doesn't have
to be in Jace Informant. It can be any four months to choose for our case. Let's
use Jason for that. We need to import system, the text or Jason. So let's add using
safe and by pressing enter. There we go. Let's give this a try. Let's send that
request to get the first page of deed again. We get back five alters. So far, so
good. Let's have a look at the response headers. There's our ex pagination header.
There's no previous page link, but there is a next page link. By the way, as you
can see, a speedboat netcord serialize er automatically escapes unsafe characters
in Jason. It's safe to send over the water like this. But if you don't want this,
you can still manipulate this, bypassing two adjacent serialize her options Object,
or you can use jayson dot net all right without recovered. Beijing Let's have a
look at the model summary.

Summary
[Autogenerated] paging can be very good for performance. If don't correctly, we
should pause The Babe sighs and page number fired a Query Street. Think about
limiting the page size that's passed in to avoid consumers requesting one page with
a 1,000,000 records. In other words, make sure to provide default values for page
size and page number. Also, imagination. Meta data belongs in a custom header. When
paging, it's important to send page size and number two the underlying store like
that. Only the requested page is returned from the store, thanks to deferred
execution to principle that allows us to keep building a credit before executing
it. We can use, Skip and take statements for that also, page by default to avoid
performance issues when the collection grows. For that, we created page list class,
which can easily be reused for other resources. Lastly, it's important to return
pagination medal later, so the consumer knows how to navigate to previous or next
pages. And how many records aren't in the database that meta data belongs in a
custom header, for example, X pagination. That's it for Beijing. There's another
piece of function out of the awfully quiet for the FBI's sorting. We're covering
that in the next module

Sorting Resource Collections


Coming Up
[Autogenerated] a lot of FBI consumers expect a P I studio turned sort of data
ascending or descending and all different fields. This is not revealed to implement
if you want it done right. Nevertheless, in this module will learn how to do that.
I'm Kevin L. Guy to Truitt. We ended the last module by implementing paging
functionality, but a lot of AP eyes required additional functionality. A consuming
application might want to choose how to order the resources in the list not only by
one field but by multiple fields, boat ascending and descending. This will require
quite a bit more plumbing than what we did in the previous model, but the advantage
is said by implementing it like we're going to do it, we'll end up with reusable
parts that can easily be used with other collection resources. Let's dive into
sorting

Sorting Resource Collections


[Autogenerated] the next piece of functionality will want to implement for alters
Resorts is sorting. This is a bit different from what we've done with paging in the
scores and filtering and searching in the beginner course in regards to passing
through parameters, which filtering, we provide a value for a specific field from
forming category, for example, with searching. We also provide one value for the
search query. But when we soared, well, let's have a look at a few examples. A
simple example would be ordered by equals. H. That's a long lines of what we know.
One value for an order by Kloss Important here is to remember that our outer facing
model I dd oh, model is different from the end of the model. In case you didn't
feel the building arrest for a P I with the sp dot net court recourse. That's
quickly recap why that's the case. The end of the model in our key issues by entity
framework or represents database rose as objects. The outer Facing Model or D T. O
Mobile represents what send over the wire, and these are not necessarily the same
taken older, for example, On screen, we can see some pseudo code for that on all
restored in our database with the date of birth. But that date of birth, well, that
might not be want. We want to offer up to the consumers of the A P I. They might be
better off with the age. Another example might be concatenation contaminating first
name and last name from an entity into one name. Field in the resource of
presentation. And sometimes data might come from different places. Unaltered Could
have a field, say royalties that comes from another a p i r a. B. I must interact
with that. Lone leads to issues when using entity classes for the outer facing
contract as he don't contain that field. Keeping these models separate leads to
more robust, desired. Leave all verbal coat. Imagine having to change the date of a
stable that would lead to a change of the entity glass. If you're using that same
and declasse to directly exposed data via the FBI, our clients might run into
problems because they're not expecting an additional renamed to remove field. We're
essentially making version ing very hard, because by reusing those entity classes,
the database can't evolve separately from the a p I. So that's why these model
should be separate. But that has an impact when we're going to soar. Sorting
statements relate to the fields of the resource i e. The DDO and not to whatever
lies beneath that layer. It might be different in the backing store, in our example
on altar as an age in the results of the presentation. In the underlying data
stored, there is no age. Instead, there's a date of birth. That means we allow
sorting on age and not on a date of birth, because we should never expose what's
happening behind our outer facing contract. Let's have a look at another example
Order by equals H desk. Well, that's different. We're now also stating how we
should order descending. Still, one order by Klaus but in our coat will have to
take into account that one part of the string is about a field, and another part is
about the direction, and we can go beyond that order by equals. H desk name Sorting
typically doesn't stop. After the collection he sorted on one field, you might want
to sort on age first descending and then another field name. So that's another
thing we have to take into account when implementing this. This will require some
work, but it'll be worth it. Let's dive in.

Demo - Sorting Resource Collections


[Autogenerated] in this day more we're going to implement. Sorting will allow
sorting on all fields, ascending and descending in order and possibly combined.
We're not all this controller. They get all transaction, must be able to accept an
order by credit string parameters. So let's make sure we can accept that all we
have to do is added to our altars, resource parameters, class. Let's also give it a
default value, say name. That's a pretty good default sorting order for a bunch of
alters, and the consuming application doesn't like it. It can still pass through
another value or even just in empty string. But it immediately also confronts us
with an issue. Name is a property on the DDO, but not on the underlying and
remodel. We need to map this. That's open the depository. This is our get all to
smell it on the repository. We're already filtering in searching here. So after
that, let's at ordering as long as the default value is used name. We should order
on first name first, followed by last name for that to be used order by followed by
then my Now this is only valid when the order, by claws its name. So let's add
another check to that of ____. We surrounded order by statement with any statement
and another statement. We check if the past true order by value is indeed name.
Let's give that a try were imposed, man, and I've got a request lined up here.
We're getting all the olders and we're ordering them by name. Let's send it. Let's
have a look at those names are no old Addison Berry dwelling. This looks like it's
ordered by name. So far, so good. Back to our coat. The problem with goat like this
is that it isn't very reusable. Imagine having to write code like this for 10
properties, which can all be combined in ascending and descending order. That's not
very pleasant and quite error prone, but we do need to map this somehow. So what do
we do? Well, we can write a mapping service that maps a name string to a first name
and last name Street I, from the property names on the video to the property names
on the entities. That's part one. Secondly, we need to be able to apply the
sorting, but what we get our strings And if you look at that order by Klaus, there
isn't a single overload that accepts a string. And we really want to avoid having
to ride a huge switch statement for all possible sorting combinations. Luckily,
this isn't a new requirement. In fact, it's for these types of requirements that
Microsoft create the system, not Ling. The dynamic library. That celebrity that's
been around since, I think 2000 and eight, and it's one of the most popular link
extension libraries. Luckily for us, it's imported to a speed of net core fire.
That library we are able to sort on streets. So let's open. You get dialogue and
search for it. What we want to search for system don't link the dynamic dot core.
Let's install it back to our depository. Okay, we should now be able to soar by
string. But doing all of that in this repositories method won't exactly Lee to
reusability. And that's what we need. Because doing something like this is
something we'd like on all resource collections, right? We can separate that out
into an extension. Methadone. I credible. So what we want to end up with is some
sort off apply sort extension method, which we should be able to apply on anything
I credible. It should accept our order by string so we know what to order by and a
mapping dictionary, which we still have to create. That mapping dictionary can then
be used to know that when a consumer wants to order by name, we actually have to
apply older by and then by methods on first name, last name. Let's think about how
we're going to create all of this.

Creating a Property Mapping Service


[Autogenerated] so we can have sorting a multiple field names of the resource. But
one resource property might map to multiple properties on the entity. For example,
the name property off the order a video is a concatenation of first name and last
name on the entity. Moreover, we're going to allow sorting, ascending and
descending. And in the case of age, that will be an issue. The higher your age to
lower your date of birth. So in that case, the past in sorting direction should be
reversed. We could just create a hard coded list. But let's make this reusable.
We're going to create a generic property mapping service and register it with their
speed of net courts building container. Now, how do we do that? We'll need a
property mapping service class. It implements interface I property mapping service
that allows us to register it on the container on interface instead of directly on
implementation. This service holds a list of property map things like one that maps
the properties. We can sort on often altered video through the fields on the
underlying data store. One such property mapping from a source to a destination,
then holds all the wrappings from, for example, the altar video fields to the altar
entity fields. That's a dictionary. A simple monk could be i d maps to i D. But as
we know, that's not sufficient. One field on the resorts might map to multiple
fields on the entity like name to first name and last name, so the dictionary
should have the field name off. The resort is key, but another classes value, and
that's the property mapping value class that one should ankle the analyst of
Destination Properties. With that, we can map the name field to first name and last
name, and we'll also need something else. As mentioned in case of age, the sword
direction could be reversed when we sort ascending my age. That actually means we
sort descending by date of birth, so our property mapping value should also have
revert property. With that, we have all the information we need for our map ings on
our property mapping service. We should have never mattered to get a specific
mapping, get property mapping from source to destination, for example, from all the
detail to the altar entity. We'll have to create all of this, so it is a bit of
her, but in the long run, this really helps towards reusability. Let's dive in

Demo - Creating a Property Mapping Service


[Autogenerated] in this demo will create the property mapping service we just
looked into. But let me start by commenting I artist code from the previous table.
This isn't working at the moment anyway, but it will in a while. So let's start by
adding a property mapping service class to the service's folder. So the name is
property mapping service. We know this service has to contain a list of property
map things, and a property mapping intern contains a dictionary with a key off
string and a value off property mapping value. So let's add. Have property mapping
value class next. This one contains an eye innumerable of string. Those are the
destination properties. One resource property will map, too, and it also contains
revert bullion, allowing us to divert to sort order. If the we also add a simple
constructor, making it easier for us to create such a property mapping value.
Object back to our property mapping service and let me based in the map. Things
were going to use to map from unaltered video to an altar entity. So here's a
dictionary with a string as a key and a property mapping value as a value we're
already using that constructor we just created off importance here is that we can
map from age to date of birth using reverse ordering and from name to first name
and last name. Then let's add that mattered to get one property mapping. True, this
will be able to ask for a mapping from a source type to a destination type, like a
mapping from unaltered video to an altar. But we haven't got a class to hold such a
property mapping yet, so let's add that well named is one property mapping as we
want to map from a source type to a destination type we passed through to die
parameters and do it. We add one property, the mapping dictionary, off string
property mapping value. Next to that, we also add a constructor too easily.
Construct objects like this and that already takes care of the tree classes from
the sides. Let's go back through the property mapping service. We can now add an
eye list off property mapping from T source to de destination, but there seems to
be a problem with this D source and D destination cannot be resolved that can be
overcome by using a market interface that's an interface without any medicine. It
it's often used for cases like this. If we let our property mapping class
implemented marker interface, we can register an eye list off that market interface
that's at one I property mapping. Sounds like a great name for a market in the face
for a property mapping. And let's have our property mapping class. Implement is
interface back to our property mapping service and how we can store and I list off
i property mapping named property map ings, which we immediately insensate to a new
list to avoid null reference issues. There we go, then that's Attica instructor.
And in this constructor, we can now add a new property mapping from a source or the
video to a destination. The altar entity passing through Alter Property Mapping
Dictionary, which contains mapping, is between all properties from an altered video
to an older entity. We do have to import some names. Faces altered video is
defining course ivory, the FBI top models. So let's add using statement by
pressing, enter and alter is defined in courts. I relay be idled entities, so let's
have the using saving to that name space as well. So we now have a list off my
property mapping we can search. All that's left in this class is implementing to
get property mapping method. First we find the matching mapping by searching our
list off I property mapping for property Map things from the past in source type to
the past in destination type if you find exactly one meter in the dictionary.
Otherwise we drew an exception. That's it for this class. Now let's create an
interface from this so we can magistrate as an interface implementing clause in the
container. We'd like to think the glass name we click on quickly factoring Tze and
we choose extract interface. We only need to public get property mapping member so
that's okay And there we go graduates during these on the container is down into
configure service meant it in the start of class. Transient is a lifetime advised
by the sp dot net core team for lightweight stateless service is so let's register
it as such We that's we can now inject our property mapping service where we need
it and get the mapping dictionary. Let's do that in the next day. Mo

Demo - Creating a Reusable ApplySort Method


[Autogenerated] in this table will improve our coat by using our freshly created
property mapping service in a reusable extension that it apply sore that that it
will be called from the depository. So let's open Net repository. We'll need access
to the mapping dictionary. So let's inject the mapping service in repositories.
There we go. Let's call down to our get alters. Met it. We still have our apply
sort method here from a previous table. It's not implemented yet, but the signature
is okay, So the first thing we need to do is get that mapping dictionary. All the
video is defining course. I redid AP Idol models. Well, let's make sure we used the
cortex variable name and there we go. So we now have the property mapping
dictionary. We have the order by Klaus. We're passing through to the applies for
Admit it. But we don't have the apply sword metal itself here. That's what we still
need to write. So let's have a new class to the helpers folder. Apply Sort is gonna
be an extension. Methadone. Incredible. So let's name glass eye credible
extensions. We want to make it static, as we're going to use this class without an
extension matatu. And let's add the apply sword method. This matches the signature
we use in already Paul's story. Property mapping value is defined in course I
vetoed. A vital service is so let's have a using statement by pressing enter. We're
also going to be using dynamic link. You remember that from to day most ago. We
need that to be able to sort on strings. So let's have the using statement to that.
There we go. The first thing we want to do is check our input. So if the sword is
now, in other words, if the eye credible will applying the sort meant to it's no
retro and are given no exception. We also true an argument, no exception. If the
mapping dictionary is no, and if there is no order by close past ID, we simply
return the source as there's nothing to order by. All right, that's it for checking
in boats. Then we want to split the order by street as we remember from the slides
on order, Biased thing is separated by a comma, so he splits on comma. What you
want to do next is apply each order by Klaus in reverse order because otherwise the
I credit will will be ordered in the wrong order Between the order by Klaus these
fields are passed into the credits tree so they might contain leading or trailing
spaces. If the sword option ends with DSC, we want to order descending, otherwise
ascending. Then we need the actual property name. This is the name of the property
on the detail we want to order by. That means removing S C or D S C from the order
by calls. At this moment we have the property name there. We need to check if our
property mapping dictionary contains a mapping from this property name to property
name on the entity. So we search for that. And if they're lapping is missing. We
drew an exception. If there is a key matching the property name, we get the
matching property value. We do have to make sure it's not No. So we include a check
for that as well. And then we can do the actual sorting using dynamic link. We
don't throw all this nation properties in reverse order to ensure that the order by
causes are applied in the correct order, if necessary. Reliever to sort order. And
once all that is done, we call into ordered by on the source, passing through the
destination property and the sword direction. When all of that has been done for
each property, we can return the source. All right, that's it for this method.
Let's look back at our depository. Our apply sword method now resolves. So far, so
good. We could also get rid of this order by statement from the previous day. Boom!
As we're now using the apply sort matter and before we forget, let's make sure we
set the collection to the sort of collection. All right, let's save and let's give
this a try. First of all, let's send a request to get the altars again for this
request. No explicit order by Klaus has been passed through. That's quicksand, and
we get back our altars ordered by name. That's because that was the default sort.
Or do we provided All right then that's effectively ordered at my name and see what
gifts. There we go. Same result. Let's try ordering them my name descending. You
know, Dad, by passing through name space, the SC as ordered by calls. And there we
go. S R R n looks like this is ordered by name descending. Let's continue. Name was
a field that translate to two properties on our entity mean category. Well, that's
a direct mapping. So let's try sorting my dad. You haven't tried this yet. And
there we go. General debauchery maps, maps, maps, maps, rum Looks like this is
correctly ordered. Let's combine this with that other special field. We had age
that map to the date of birth, and it should reverse the sorting order because the
higher the age, the lower the date of birth, let's send this request. So the first
thing you notice is that we are still ordered by me and category first. But if you
look at me and category maps, we now see that were ordered by age inside of that
category as well. So far, so good. Let's have a look at the response centers. If he
would now navigate to the next page link, we would lose our sorting order as the
order by Klaus isn't in net link. That can't be right. Let's fix that in the next
evil

Demo - Adding OrderBy Clauses to Pagination Links


[Autogenerated] in this demo will make sure our order by calls is available in the
page in nation links. We kind of know how to do that already, as we did the same
for filter and search credit in previous module, we're looking at the create alters
resource you where I met on the oldest controller here. We need to ask the order by
close, and we need to do that for the previous page link, the next page league and
the default. All right, let's give that a try. Let's send that request again. This
time, the next page link does contain the order by close. Lastly, let's try sending
an invalid request. We're going to try and order by date of birth. That shouldn't
work because there isn't a mapping. Define for that we have an exception. So far,
so good. And we get back 500 internal server and or with the stack trees in
responsibility. So the goat works, but we're not quite there yet. When the consumer
of the A p I makes mistake, he should get back and editor in level 400. Well,
because you were made a mistake. He provided invalid input so we should get back a
level 400 errors. In other words, it's not because our code works that were rest
ful. We're not adhering to the HDP standard that it's more. Let's check out how we
can fix that in the next table.

Demo - Taking Consumer Errors into Account When Sorting


[Autogenerated] What we want to do is admit it the checks for invalid input we can
then use that result in to get all this action to return to correct status code. So
when it's an order by invalid due to a consumer mistake, well, we decided on that
before it's invalid. When he or she asks to order on the property for which no key
in the dictionary exists, that dictionary is defined on our property mapping
service. That doesn't mean that if this checks out that other issues might know the
rise, for example, we might introduce an unwilling buck like making mistaking a
mapping or providing the wrong wrappings to the apply sword action that can still
result in exception. Or it might pass without us noticing it can simply be a buck.
Those are not mistakes of the consumer of the A P I. So what we need to do is check
if forgiven, string off fields like our order by string. There is a valid mapping
dictionary that contains mapping is for all those fields. So the property mapping
service we're looking at looks like a good place to add such matters, too. So let's
add it. Let's name it. Valid mapping exists for source to destination it except a
list of fields. First, we use guest property mapping to find to property mapping
from the source to the destination. If no fields have impasse, true really turn
true. No mapping needs to exist if you don't have an order by Klaus. Fields are
passed through separated by commas. So we split on comma and then we run through
all the fields between them and we insure that anything related to sorting orders
ignored. We don't need to sort order. In this case, we simply need the field names.
Once we have the correct property or field name, we look for the matching key in
our property mapping dictionary. If that can be found, return falls. If he checks
out for each and every field. Really turn true. All right, let's save this and
let's go to the office controller. In our get all this method, we want to check if
he ordered by strings Follet. So we can really turn a bad request. If it isn't,
that means we need to inject the property mapping service in our controller. There
we go. And in our get alters method we call into the valid mapping exists for
methods on the property mapping service. We boss through the source type, the ultra
video and the destination type. That's the altar entity We also passed through the
older by close. It appears it cannot resolve the valid mapping exists for a minute.
You forgot one little thing we defined. Valid mapping exists for on the property
mapping service. But remember, we're working on interface, so we need to add that
matter, buddy. I probably mapping service interface as well. There we go Now. Let's
look back at our controller and there we go. Valid mapping exists for can be
resolved. Let's give this a try. All right, let's try sending that request again.
This time we get back a 400 bat request. So far, so good to end this module. Let's
combine a few things. Let's try getting the first page with a page size of two off
all the orders ordered my name, which haven't a in either their first name lost him
or being category and for whom the main category is Rob. This combines the
functionality we implemented up until now and there we go. So far, so good. So we
just implemented automatic sorting on all fields. It was quite a completed teacher
to add. But all you know, not even that much work to get sorting functionality in
all fields ascending and descending. And our code is reusable for other resource
collections. An interesting fact is that we can use the same technique for
filtering if we want to allow it on all fields. Use the mapping table to find out
how a property on a resource maps to the underlying store and use dynamic link to
create where causes. And with that, we now know how to sort. Let's have a look at
the module somebody.
Summary
[Autogenerated] When implementing sorting functionality, it's important to keep a
few things in mind. Collection resources are typically sorted on multiple fields.
Often the sorting direction has to be taken into account. Sorting can only happen
on resource fields, and Nolan feels that lie beneath that layer. That requires a
bit of plumbing because otherwise you'll end up with a set of large switch
statements. We solved that by writing reusable mapping service and reusable apply
sort extension method. The order by parameters must also be returned to Beijing
Asian links. And lastly, adults relate to wrong input Our consumer editors and
should just be returned as a level 400 error. For example, about request. There's
not a piece of functionality that is sometimes supported by rest ful AP eyes. It's
called data shaping or shaping resources. Let's have a look

Shaping Data
Coming Up
Data Shaping Resources
[Autogenerated] Let's talk about shaping resources. Word kind of gives away what it
does. This principle allows the consumer of the A p I to choose the fields off the
resource. Does that have to be returned? So rather than returning all properties
off, say, on altar consumer oven, a p, I might only need to know the idea. And the
name data shaping allows for this by looking at a Fields credit string parameter
off which value is a comma separated list off field names. Implementing
functionality like this can be very good for performance. In case of our older, the
impact will be quite small, But just imagine a resource with 30 properties off
which the consumer needs a collection off 50. But he only needs to feels without
data shaping 1500 property values would have to be sent to the consumer. With eight
are shaping on Lee, 100 will be sent That does have a noticeable impact. What's
important here justice for filtering and sorting is that this field level selection
isn't level off the resource field names past in US value for the fields. Credit
string parameter should exist on the resource. So for our order. The field level
selection on age is foul it as the altars resorts has an age, but one on date of
birth is not fell. It as an alters resort doesn't have that The date of birth is
defined on the entity, not at level of the outer facing contract. Let's have a look
at how we can implement this.

Demo - Creating a Reusable Extension Method to Shape Data


[Autogenerated] in this demo will create a reusable extension method to shave data.
First, let's have a look at what returned from or get alters action. You see that
it's an eye innumerable off alter video, but with data shaping, we no longer want
to return. I innumerable off the video, we want to return I innumerable off a new
object, one that only contains the requested fields. We need a way to dynamically
create an object at runtime starting from our old video. So we're going to work
with dynamically type objects in this day well, and this is where the expand the
object comes in. Expand Object represents an object whose members can be
dynamically added and remove that one time. The extension that we want to create It
stirs a matter to that extent. I innumerable off D, except our fields and returns
and I, innumerable off dynamically type objects, expand the objects that only
contain the fields requested. That's at a new class toward helping Fuller for that.
Well, name it. AII innumerable extensions. It's going to contain an extension med
it, so we have to make it static lane. The method shape data. It should return I
innumerable of expanded object work on I innumerable off a type D source and accept
the fields parameter expand. No object is defined in the system that dynamic name
space. So let's add a using statement by pressing. Enter first things first, we
check if the sword doesn't know if it is. We throw an argument, no exception. Then
we create a list to hold our expand objects. It stood this list that we're going to
add expand objects that only contain the fields we need. We're going to use
reflection to achieve what we need. But reflection is rather expensive. So instead
of doing it for each object in the list, we do it once and reused results. That's
why we create a list with property in four objects on the source. Property info is
different in system, not reflection. So let's have the using statement by pressing
Enter. It contains information on a knob Jek property. If no fields have been in
but it it's quite easy. We want to return all public properties in the expanding
object, so we look for the type of tea source, and on it we call get properties
both public and on instance that returns a list of property in force, which we
don't add to the property in fullest, it feels have been passed through. We have to
do a bit of extra work. First of all, we split the fields, retrieve each field as
they might contain the north, trailing spaces. Now we have the property name and
from that property name we now need to get to property info. So we get the type of
the source, and on it we call get property passing through the property name. We
ignore the case and we want to get all public and instance members. If no property
info has been found, we drew an exception. Otherwise, we added to the property in
fullest. So at this moment, we have a list off property in force of all the
properties we want in our expand object. Then we need to get those from the sore
subject. So we run through all the sore subjects, and for each sword object, we
create a new object and expand the objects. Then we need to get the value of each
property we have to return. So we run through the property in fullest we call get
value on the property info passing through the sore subject that will get us the
actual property value. And then we add that field for new data shaped object that's
an expanded object. And beneath the covers and expand our object is actually a
dictionary of string object String. Being the key is the property name object is
the property value. So we add a new property with the name from the property in for
object and the property value we just got once that's been known for each property
we need, we add a new expanded object to our expanding object list. And lastly,
really turned that list. That's it for our data shaping extension method in the
next table, we're going to use it.

Demo - Data Shaping Collection Resources


[Autogenerated] in this day. Mo. We're going to add data shaping support. What a P
I we're looking at are get older. Spent it in the orders controller. First thing we
need and this is becoming predictable is a way to pass the fields. We want to
return to our A p I. So that's open the olders resorts parameters class, and let's
add a new string to it fields that takes care of that vector to get alter. Smell
it. Now let's think about what we need to do in the previous day. More. We created
an extension matter to shape our resources. That means we won't be returning an eye
innumerable off altered video anymore, so we should change the action signature.
You can't use actual result off D anymore, and that's a bit of a disadvantage. But
using I actually result in a case like this is more correct. Let's cool down a bit
on the collection of alters we call shape data, and we passed through the fields we
want to see returned. That's it for data shaving, but just a sweet sort in the
previous module, we need to make a small change to the create all those resorts
where I made it. We need to ensure we passed through the fields parameters when
creating the previous and next page links. That's it for the previous page. We do
the same for the next page and for the default. Let's give this a try. Let's and
request toe only fetch the idea of an order. We do that by passing through I d as
the value for the fields credit string parameter. And there we go. Now let's try to
fields I D and name and there we go works as expected, we just implement data
shaping for a collection resource. A list of alters. But what about shaping a
single altar that might look easy just to reuse this extension? Made it right.
Well, yes and no. Let's have a look at the specifics in the next table.

Demo - Data Shaping Single Resources


[Autogenerated] in this demo will implement data shaping for a single resource.
We'll need another extension metaphor that this time on object instead of on a ny
innumerable of object. This might feel redundant at first. Why not just write a
shape data metal object and reuse that for each object in innumerable? There's a
good reason for that. I will get to it soon. First, let's at that new extension.
Let's have a new cost of the Helpers folder. Now let's name it object extensions.
We may get static as it will contain an extension middle. And let me based in this
extension at it, it's going to look fairly familiar. Now. Why do we have to
extension? It's one shape date. I'm after all, an object and another one on
innumerable. Why not call into the shape data mattered for each object in our
orders list? Let's put these methods next to each other. There's one big difference
between the shape Data Med. It's on object versus the one on innumerable of object.
The reason is performance, as explained when we implement the shape data about it
on I innumerable off the source reflection is expensive in our shape data matters
on my innumerable T source. We get around that by saving a list of property info
objects, and we re use those for each object in the list. That's what you see on
the bottom part of the screen on the top part of the screen. You see that we don't
save such list. It's simply get the property info we need for this object as we're
only working on one object. But were we to use the shape data extension methadone
object the one on top of the screen for each object in the list of orders, we'd
have this additional piece of reflection for each object. By creating two extension
methods, we avoid this performance impact. The rest of the shape data metal object
follows the exact same logic as the other one. All right, so far for that that's
used this new metal. We're back in our old is controller. But this time we're not
working on the collection of orders were working on a single order, So we need to
look at the get alternative. The first thing we need to do is allow passed in the
fields. We want to see returns. We don't need a containing class. Like all this
resource parameters this time, there's only one parameter that can be passed
through in our case. Fields ride before returning. Okay, we call shape data on our
object, every pass through the fields. Let's give that a try. I've got a request
lined up here to select fields I. D and name from one specific old. Let's try
sending it. And there we go. We only get back the idea in the name. So far, so
good. Interesting fact here. By allowing data shaping, we could potentially violate
arrest constraint. The manipulation off resources through representations
constrained to be exact that one states that when a client holds for the
presentation of resource, including any possible meta data, it should have enough
information to mollify or delete a resort on the server provided it has permission
to do so. Security knowledge. Hearing to that. Yet we're just returning an I D. And
to a deer to it. We should either include the resource you were I in response or
better yet, support hate us. That's coming up next, but let's imagine the I D is
urges, or she would die for a second I can simply not selected. Let's send this And
there we go. We only get back in name. So this time we don't even have that I d
anymore. And that can't be good. We are definitely breaking this constraint, so I
just want to mention this year already because not all a B I support hato us. If
you don't want to support hey to us and you're opting to add the resource you were
I to each response, make sure you don't allow data shaping to amidst this your eye.
This kind of proves that it's not always that simple to a deer to these constraints
and design a truly rest ful system. Before we know it, we introduce functionality
that breaks our architectural style. There's two more requests lined up here
shaving altar by requesting the first name and the same for shaping alters. Let's
try that we have an exception, and that makes sense. Property first name doesn't
exist on our altar ddo. Let's continue when we get back, a 500 internal servant
enter, and that's not right. This is a client, so it warrants something in Level
400. Justice was the case when we were sorting our resource collections. Let's
learn how he can fix this

Demo - Taking Consumer Errors into Account When Shaping Data


[Autogenerated] to correctly implement the http standard, we need to return a level
400 errors like bad request. When the consumer makes mistake by inputting an
invalid field to shape, we're looking at the gets Alter Smith. Theoretically, we
could reuse the cheque reprieve Issue Road for checking the order by cause,
however, that would be correct. It will work because we stayed that we need a
mapping for each property. So for all our fields on the DDO, mapping, Sze will
exist. But our data shaping component doesn't use that mapping dictionary. So if
you have a resource collection that supports data shaping but not ordering well
without look, and it's also not a good separation of concerns. First, it's better
to keep these separate. What we need to check is that for a given string of fields,
all properties matching those fields exist on a given time. Let's create a service
for that so we can use air speed on that course build in dependency injection
mechanism. We want this to be reusable and injectable wherever we need it. So let's
add a new class to the service's folder and let's name it property checker service.
We add one method to it. Diapers properties it except a string of fields. So how
does this implementation look? It's much like our shape data about it, but shorter.
So let me pasted in. If no fields air passed in, we can safely return true.
Otherwise, we split the fields and run through all the fields. We treat each field
to get the property name and used the get property method to check if a property
with that property name exists. If one can be found. Really, Turn falls and evil
checks out really turn true. That's it, for that matter. Now let's extract an
interface for that service. We do that by right clicking, choosing quick actions
and re factoring Sze and clicking extract interface. We want to extract the dive
has properties mattered So all of this looks Okay, let's click. Okay. And there we
go onto our start of class so we can register this just as our property mapping
service. The property Checker service is a lightweight and stateless service as
well. So transient is a good life. Time for it. Back to our controller. Let's
inject this service. There we go in the ghetto alters methods we now call into type
has properties on this service passing through the type altered video. We also
passed through the fields. We expect this type to have if he doesn't check out
really turnabout request. Let's scroll down a bit to the get altered action here.
We had the same type of check this time using the fields parameter. Let's give this
a try. We've still got our request lined up here that's failed in the previous
table. We're selecting the first name from one specific order. It used to return a
500 internal server ever. Let's see what happens now. This time we get back a 400
bat request. So far, so good, just to be sure, let's check the same for the altars
resource. And there we go. Let's have a look at the other options we have with data
shaving

Exploring Additional Options


[Autogenerated] there are a few additional pieces of functionality we could
implement in our A. P. I. The data shaping principle can also be used to also
include child resources. One option is using a new expand parameter combined with
the fields parameter. Another option is incorporating this into the fields
parameter. If it includes a field, of course, is it should include the courses
collection, something else that's sometimes seen on a pea eye's not related to date
are shaping its using more complex filters like contains filter. The example on
screen should return all orders off each. The name contains Kevin. The more of that
we allow, the less we might need searching functionality and so on. If you want to
implement functionality like that, you can build upon what we did in this and
previous module and in the building rest for a P I with the S people, not court
recourse, but think well about how you want your a p I to be used. There is no need
to implement all of this functionality if it is not something you'd expect
consumers off the A p I to require. Just remember, Boss Parameters fired a query
string and only use fields that are part of the resource, not off objects related
to lower level layers. Let's have a look at the summary.

Summary
[Autogenerated] when implementing data shaping functionality, it's important to
keep a few things in mind. Data shaping can only happen on resource fields.
Northern fields that lie beneath that layer once the glasses shaped, it's no longer
your original diet. Working with expand Oh, object makes it easy to create these
types of objects for performance reasons. Don't reuse the same method for shaping
collection resources. Then you would use for shaping single resources. Fields
parameter must be returned in page nation links and adults relate to wrong input or
consumer letters and should just be returned as a Level 400 ever. For example,
about request, we mentioned Hato as a few times we can use it to a dear to the
manipulation off resources by our presentations constraint, and additionally, we
learned that it can also be used for pagination medal later, which will tie into
the self descriptive message constraint. So it's about time we cover that right
onto the next module, learning and implementing Hato US

Learning and Implementing HATEOAS


Coming Up
[Autogenerated] hate Wes is an often misunderstood and undervalued rest constraint.
Yet it allows for some really cool scenarios that are very useful in an enterprise
environment. In this model will learn all about I'm Kevin. I'll guide you through
it. So only one subject this time hyper media as the engine of application state.
One of the sub constraints off the uniforms interface constraint in this module
will cover what it is, exactly what it helps with and how we can implement it in
different scenarios. It's quite a big subject, so let's dive in immediately.

Hypermedia as the Engine of Application State


[Autogenerated] Currently, our FBI is already quite good, but it's not exactly
evolve herbal, nor is addressed ful. Hate us will help with this. It makes a P I C
voluble and even self describing They hate us. Acronym means hyper media as the
engine of application state. In other words, hyper media like links Dr how to
consume and use the A p I. It tells the consumer how it can interact with the A p
I. Can I delete this resource? Can I update it? How can I create it? And how can I
access the next page of data and so on? But what problem does it all imagine? We
want to allow the consumer of the A P I to update or the lead, of course, currently
does not know how to do that. By looking at the response, it has to have some
intrinsic knowledge of how our a p. I contract this structure from the contractor
documentation. The consumer can learn that he'd have to send the foot or patch
request to a P I olders alrighty courses. Course I d to update the course with a
specific payload and a delete request to delete it, but it cannot get that
information from the response itself the consumer has to notice involves. So that's
one issue. Now imagine another use case. Let's say we have an additional field
number of available places on our course. If there are still places available,
someone can sign up for the course. In this case, the consumer of the A P. I will
have to know it has to inspect that field before it can send the post request to,
say, a P I course reservations. That's again intrinsic knowledge of how the FBI
works, just as in the previous example. But say these changes say on additional
rule is implemented. There have to be places available. But if the user wants to
make a reservation for a court that's marked with content mature like courses
dealing with rum, he or she must be older than 16. This rule will effectively break
the consumer off the A p I. You have to implement that on their side as well. In
short, even a p I doesn't support hey, tow us to consumers of the A P. I have to
know too much, and if the AP I evolves this might break the consuming applications
because the assumptions made by those applications can become invalid. And that's
the issue that Hato assaults. A lot of these assumptions can be thrown overboard by
including links in the response that tell the consumer which action on the A. _ _ _
possible and those links? Well, those are hyper media. So hate us allows the FBI to
truly evolved without breaking consuming applications in the end, resulting in self
discoverable AP eyes. So in our example, we could add an additional property legs
to the response. The current would just have to inspect these links. The first link
could be linked to get the resource itself. I abbreviated to the bits in the code
for readability, but it must be a true link. So with the correct host and go, it's
for the altar and course I D to update a course in full with put and partially with
Patch leagues are out of this. Well, if that functionality is offered by the A P I.
If the leading of course is allowed, we add link with your eye and metal to the
lead, of course, and if we deserve course, link appears our reservation for a place
on the course can be made, so it's up to the server to decide whether or not to
show these links. The consumer needs no knowledge about that business rule, and
moreover, the rule can change without having to redo anything. It climbed level. If
all of a sudden we expand rule stating that there must be places left and that the
user must be over 16 to reserve a court marked with content mature, this is no
longer rule that has to be checked by the client. The server would simply not
include tattling to make the reservation, and the client only has to inspect
whether or not link is there to say show about him to make a reservation. Let's
have a look at another Roy feeling quote guy. We haven't addressed. You can't have
evolve ability if clients have their controls baked into their design at
deployment, controls have to be learned on the fly, and that's what hyper media
enables. This girl goes quite far. If you match this to building applications,
we're almost talking about self generating client user interfaces. Most
applications don't go that far, but as the example we use teaches us for things
like rules that change. This is pretty great, and additional pieces of
functionality can be added. For example, marking a course as one of your favorite
courses in that case on additional link will be provided. This will not break
existing Klein applications, but from that moment on, they can implement
dysfunctionality starting from that link. Now, if we think about this, that's
actually nothing more than how we should work with the HDP protocol. Leveraging
hyper media rest evokes an image of how good Web application would work, and while
on the Web, it doesn't really matter. Everything changes. We typically start at a
route your eye of a newspaper side, for example, and from that we navigate to an
article by clicking on a link or submitting a common to a form. That's two examples
of hyper media driving application state. And if the server decides that the link
should change well, the request that return to root page will contain that new
link. The browser, which is our application in this context, doesn't break because
the link changed. Instead, it's the hyper media in response that's used by the
browser to show us what we can do next. Okay, now, what do these links look like?
Jason or XML? Don't have a notion on how to represent links, but HTML does the
anchor element in HD well, h ref contains you or I well describes how the link
relates to the resource and type, which is optional. Describes the media type for
supporting Hato us. This former is often expanded upon. Let's have a look at one of
the links from our previous example. Again, they all follow the same principles.
The Method Property defines the matter to use drill, identify the type of action.
This is what clients look for in the link list. So this is what clients need to
know. A treff contains your eye to be invoked. To execute his action. The client
simply uses this link. It doesn't have to create it anymore. Mind you hate us
doesn't completely lift the client off having to have some knowledge of what to
expect. It still needs to know about link type that can come back in other words,
dural values and whether or not it wants to use them. But we are no longer heart
coding. your eyes and assumptions in the client, you or I or assumption. Change no
longer breaks the client Any Flink gets added to the response with Ralph Value
Decline does not know about yet. It ignores that link. All right, so we now know
that Hato has definitely has advantages. But in our examples, we have been working
with one order I a single resource. The links are just simply an additional field
in the response. But what about collection resources? I alters for collection
resources. We will need some sort of an envelope on object to hold value, which is
the list of orders, and the league's worried to just add in area of altars and then
a lynx property, which is an array of links we'd have invalid chasing. So the
result is in the value field while the links are in the legs field. This might be
the moment when you're thinking, Wait a minute, this doesn't make sense. When we
learned about Beijing, we learned that we couldn't use an object like this with a
value feel, too old a daughter and a meta field of all the pagination data, because
that would break the self descriptive message constraint. The government of the
response doesn't match the content type value in response. Header So the consumer
of the FBI doesn't know how to interpret the response, judging from the content.
After all, we're requesting the altars with media type application. Jason Do. The
presentation should be an area of alters. What's on screen now isn't scenario
boulders. It's an object with a value field that's an area of orders and the links
field that's an area of links. And, well, that's completely too. But it can be
fixed. We're covering that later on. For now, let's see how we can implement this
and answer a few additional questions and concerns about, hey, tow us in the next
few clips.
Demo Introduction - Supporting HATOEAS
[Autogenerated] in the upcoming demos will change our a p I. So it appears through
the hyper media as the engine of application state constraint. But how are we going
to implement this? The logic for creating the links conscious be automated as it
will depend on the business rules. For example, of course, might contain links to
abate or delete it. But also link. That's supposed to court reservations, which
only appears when some rules are met. That's the sample we used on the slides. We
can't just guess what these links might be for each resource. We'll have to coat is
ourselves. That's it. What remains The fact is that we have to add links to the
output, so there should be a lynx property on each presentation we're sending back
to the consumer of the A P I. Essentially, there's two approaches I often see used
for this. The 1st 1 is a statically typed approach. It involves working with base
and rapper classes. Get course for all to returns a list, of course video. We can
ensure that the course GTO class inherits a closet, contains links so they can be
serialized and get courses for order. returns a list, of course. So that's an
action for which we could wrap the results in a containing class so we can include
legs. That's a valid approach, but combining it with data shaping will become
cumbersome. Remember that we're working with dynamics. In that case, that brings us
to the second approach. This one involves working with dynamics and anonymous
types. If you look at what we did with the ghetto or direction, we see that that
will no longer works with the altered video. It works in an expanded object, a
dynamically type class that allows us to take a second approach. We can add a lynx
property to their expand object dynamically and for collection resources. We can
wrap that in an anonymous type. We're going to implement that approach.

Demo - Implementing HATEOAS Support for a Single Resource


[Autogenerated] in this table will implement support for hate us using dynamics and
anonymous types. If we look at what we did, we get all transaction. We see that
that one no longer returns a list of altered video. It returns an eye innumerable
of expand object to data shaped version off our altered video So we can't just
extend this data shaped object with links property through based class. For that,
we'll use an anonymous type approach. But let's start with a simpler case. One
order. First, let's add a class for our link to the Models folder. Let's name it
linked video. It contains properties for the tree values we talked about on the
slides. A treff well and method. The constructor is there too easily. Construct it
onto our get all the action. We want to add a property links with a list off links
in the response body That's Adam mattered. To create this links first, will name
it, create links for altar. To create these links, we need the input parameters off
the get all traction. So the offer idea in the Field Street Let's add a variable
toe All these links, which we return at the end of the metal. First up, the self
link. If the field strings dollar wide space, we need your eye to the orders
resource. We can again use you. It'll help her for this. We pass into out name, get
altar and then object, which were out parameters. That's the altar I d. In this
case, Terrell value itself and the method is get likewise for when there is a
fields value. The only difference is that we also passing that fields parameter.
Our FBI supports deleting an altar, so that's another link we want to add. We need
to be able to refer to this route, so we give it the name, the lead altar. Once we
have that name, we can add a link. Here's where this is starting to shine. Once the
client application has an altar, we can decide we can now let the climb application
create courts for an order. We are truly driving application state. Now we're
deciding on the functionality of the consumer. What can the consuming application
do next? In this case, it can now add a course for this altar, so we need to be
able to refer to the route to the create course for all the action. And that's on
the courses. Controller. Here's that method. Let's give that route name. There we
go back to the altars controller and let's have a leg. Azrael value. We choose.
Create course for order. Damantha disposed. We can also add information on how to
navigate throughout a P I. Unaltered as a list, of course, is so we can add a link.
So the consumer of the A p I knows how to get these courses. The list, of course,
is well, that's again an actual more courses controller. Get courses for altar. We
give the route the name so we can refer to it back to our orders controller, and we
can now add a link to it like that. We see we can drive application state through
these links if you have a link that should only show up when a certain business
rule is Matt like the example we saw on the slides. This is also the place where
you decide whether or not to include that link. That's it for creating the links.
What's next is adding these to the resource body. Let's scroll up to the get alter
action. We create links by calling in to create links for older passing through the
altar idea and the fields. Then we need to add this as we know the shape data
action returns and expand object, and that's an eye dictionary of string object. So
if he cost a shaped object to an eye dictionary of string object, we can add
properties by adding and Yuki value pair. So that's what we do. We add new property
links with our links. We just created us value. Lastly, really turned that link
resource, and we can get rid of the code from the previous day. Bos, that's safe.
And let's give this a try. I've got a request lined up here to get one specific
altar. Let's send that. And there we go. There's our links. Let's try this same
request combined with data shaping, So this time we only select fields idea name,
and there we go still works as expected. We now also see the fields parameter on
the cell flee. There's another place where we return resource ride after creating
it. Let's see if he can add hate us support there as well

Demo - Implementing HATEOAS Support After POSTing


[Autogenerated] when an older has been created, it's returned to the client. It
makes sense to also include his hate west wings. There, we're looking at the create
altered action. You've got an altar to return here. This is the object you want to
add those links to. Let's generate links first. So we used emitted from the
previous day. Mo passing through. No for the fields parameter. Then we need to add
these links to the response we need to expand the object for that. So we have to
comfort are altered video to expand to object. And that's exactly what the shape
data extension matter dust when we don't pass true fields. So we call that and then
we had links property. Lastly, we want to return this link resource. So we posited
into created that without action. This required us to input e i D. And we can get
that from the expand to object. As we know that's a dictionary of string object so
we can use the index or passing in the key. I the property name as value really
turned the link resource to return. There we go. Let's give this a try. I've got a
request line up here to create an alter. Let's send it. We get back to a one
created so far, so good, and our response contains the links property as expected.
So as you can see, we could reuse most of our coat. It's often just a matter off
riding at once. Up next is a collection resource alters. That's a bit different
from what we've done up until now. Let's check it out.

Demo - Implementing HATEOAS Support for a Collection Resource


[Autogenerated] in this demo will implement Hato as support for our orders.
Resource A collection of orders. We're looking at our altars Controller Justice
with a single altar Will want to admit it to create links Create links for alters.
This time we want to accept on altars Resource parameters object as we'll need
those to create the links it returns And I, you know, horrible, Awful in video.
Okay, let's create those things. The thing is that in this case, we've got quite a
few parameters to day care off Beijing Sword against along. Luckily, we already
have a matter refused extensively before create alters his or see where I those
will create previous and next page links, but also a link to itself. That's the
default that's returned and that one already takes care of the data shaping,
sorting, filter and search parameters next to page number and page size so we can
use this to generate legs. But it is cleaner to add another five current to the
resource. Your I type in admiration instead of just relying on the default. So
let's do that. And let's have another case statement here. ____ your aunt. All
right, now, he can go and create our links. We only need a link to self in this
case. And we do that by calling create, alters his Or should I passing in the
oldest resorts parameters and cure and s type drill itself And the matter is get
that's it. For now, the alters collection resource can't be deleted nor updating
our implementation. So on to the get older section. First, we create links by
calling our create links for all transmitted passing to the altar scissors
parameters. Then we ______ the data this returns and I'II notable of expand to
object. So we select each of them, cast the order to an eye dictionary of three
object and at links. This is the same coat as we used to get all the action. So it
again reusing what we rode before. What we need to return as set is a resort with
these shaped orders with links as value for the value field and the links for the
orders resource as value for the links field. So we created anonymous type and
really turn that you can also get rid of this gold from a previous table. Now that
should be it. Let's give this a try. Let's send request to get the altars and we
get back the first page of alters. That's because we have paging by default. For
each alter, the order links have been included. And if you school old way down, we
see that for our altars collection itself, a link has been included as well. That's
pretty cool, right? But we're missing something. Let's have a look at the response
headers. We see that we still have a potential previous and next page link here.
But should they be here? Let's learn about that.

Using HATEOAS for Pagination Links


[Autogenerated] as we mentioned when we looked into paging hate. Wes also has a
place in that these next page and previous page links are not pagination matter
later, per se. They are in fact, links that Dr Application State going to the next
or previous page so they don't really belong in the custom pagination header. They
belong in the older slinks collection. So for collection resources like our altars
resorts, this is also where it includes the pagination links that speaks that in
the next day mo

Demo - Using HATEOAS for Pagination Links


[Autogenerated] in this demo, we'll get rid of the pagination links in the custom
header and at them as hate US links. We're looking at a create links for alters
method, as that's the one in which recreated slinks. Let's add two additional
parameters here has next and has previous we can all put the previous and next
links in the link. Sorry, if has next is true, we create a link to the next page
and add it Likewise for the previous page. If has previews is true, that's already
it for the legs onto the get older section. First, let's change the pagination meta
data link Generation for previous and next page can be removed, and those two
values can also be removed from the pagination matter later. The one thing we still
after it's passed through has next and has previews to our create links for alters
metal. These can be found on the page list as we remember, and there we go. Let's
give this a try. Let's send that previous request again. If we scroll all the way
down in the response body, we see we now have a next page link. This is the first
page. So there is no previous Beijing. And if you look at the response, headers are
ex pagination Hadary still there, but has previous and has next are gone. Now let's
try paged, ordered, filtered, searched and shaped request. Let's go all the way
down and there we go. This to still works as expected, so we now know how to add
hate West links to resources. But we're still missing something to root resource.
In other words, the links to consumer will get when accessing the route off. You're
a P I. Let's have support for that in the next day, mo

Demo - Working Towards Self-discoverability with a Root Document


[Autogenerated] in this day, Mo will add a starting point for consumers of our A P
I a route document. From that route document the consumer can learn how to interact
with the rest of the A B I. The document will live at the A P I Root. So host
forward sash A B I. Let's have a controller for that. So we had a new class and we
name it root controller. We make sure that derives from controller base. That's
defining myself to the ESPN accorded every see. So let's have the using statement
by pressing enter as it's an AP I control or we annotated with the A P I controller
Attributes and row template is a P I. As we want to access this at root, we only
need while action. This time, let's name it, get root. It should be executed on get
request to forward slash a p I. So use the HDP, get attributes and will immediately
give threw out a name as well as we will want to refer to this one creating the
licks. Let's generate these links. Link video is defined in course. I redid a P I
top models So let's have the using safe and by pressing enter. And there's not much
new here what we want to generate our links to the document itself. That's the 1st
1 and links to actions that can happen on your eyes at root level or that aren't
accessible. Otherwise, in our case, that means you're right, too. Alters as courses
are children, often altar. Another link to at is an action on the orders resource,
creating one with Post. Let's have a look at that action. Drought doesn't have a
name yet, so we need to add it. There we go, and that should be it. Let's give this
a try. Let's send the get request to the A P I root and there we are. We get back a
rude document from here. Consumers off the A B. I can start interacting with it.
This looks kind of good. We just implemented Hato have support for our A P I. And
as you've seen, it's not that hard to do. But it isn't completely you, right? Let's
get our altars resource again. We are now always returning these legs, and there's
quite a bunch of them, so that begs the question. Shoot this Lynx really be part of
the disorder presentation when asking for application. Jason. This feels like a lot
of over it and bad for performance. Well, we already learned that what we're doing
now isn't a correct implementation. To fix that will have to dive into advanced
counter negotiation and media types the deeper that's coming up in the next module.
But first, let's have a look at some other options and the module summary.

Other Approaches and Options


[Autogenerated] there's other approaches we can take and what we did in this
module. There are efforts on way that describe languages for link representations,
and there's even efforts to include the media type descriptions in a resort for
presentation with legs. So we would know what to send to, for example, update. Of
course, that avoids the need for separate documents documenting it. Let's have a
look at a few notable ones. 1st 1 is whole or hypertext application language. It
provides a set of conventions for expressing hyperlinks in either Jason or XML, so
it's a standardized form of for those legs. And I'm a big fan of adopting
standards, but this one is still in draft stages at the moment. Another notable one
is siren or structured interface for represent the entities. It includes a way to
form of the links and a way to describe what send to those links. It's currently at
version 0.6 point one, so it's also not quite area, and there's more. Jason L. D, a
lightweight linked data formats, and Jason A. P I specifications for building Jason
A. P, I said, also includes way to represent legs. There's another one, and that
one is an oasis standard supported by Big Fender psych, Microsoft as AP and others,
and that so data. But oh, data goes beyond just hate West. It's an effort to
standardize rest, Phil a ___ eyes. So not only hate us, but also rules on how to
create your eyes, how to page data, how to call functions howto work with batch
requests and so on. And these are not all of them. There's quite a few others. In
other words, there's a lot coming up. But given the current state of things, it's
not that easy to decide on which one is best, especially since most of them aren't
yet standardized. Let's have a look at this module summary.

Summary
[Autogenerated] this module was focused on he to us. Hyper media like links Dr Have
to consume and use the A P I and the functionality off the consuming application.
It's st A good example would be a piece of functionality that allows someone to
make a course reservation without hate us to consumer of the A P. I must know how
to do that, typically from documentation, so it needs intrinsic knowledge of the A
P I. Even if functionality and business rules change, client applications won't
break as they need to inspect the links they get back from the A p I. These links
are included in the response body. We implemented this using dynamics, but even
though we kind of have hate us support now, we ended that last name or with a bit
of an issue. We're asking for media type application, Jason, but we're returning
links and sometimes even an envelope that can't be right. So that brings us to a
perfect use case for using media types correctly instead of just returning anything
as long as it's in Jason formal. When asking for application. Jason in the next
module, we will learn all about it

Improving Reliability with Advanced Content Negotiation


Coming Up
[Autogenerated] media types are indeed girl, if not the most important part of rest
contract. In this module, you'll learn what they are and how to use them. I'm
giving I'll guide you through it. We ended the previous model with a bit of an
issue. Are they hate us? Links part of each resorts of presentation? Or is it just
one presentation of a resource? It seems the contract between client and server
isn't tight enough yet will improve on that. Am I doing so We'll learn about
advanced quantum negotiation with media. Types will cover fender specific media
types on input and output will end by looking into an additional use. Case in that
part will dive into one off Roy feelings quotes. He once stated that rest ful AP. I
should not be versions as he is the guy who invent the trust. I tend to listen to
him, but what does that mean? And is that even feasible? At the moment, we'll cover
that as well

Revisiting the Contract Between Client and Server


[Autogenerated] Let's look back at the contract between kind and server. This light
should look familiar. The contract consists of three big concepts of consumer of
maybe I used to interact with our A P I first resort. Identify IRS. I eat, do your
eyes where the resources can be found. That's then combined with http methods like
gets to get resources posts to create him and swollen. These methods are part of
the agency to be standard. Both of these were covered in great detail in my
building. Rest Felipe II with a hospital netcord three course. The third part of
the contract is an optional bailed when creating orders or the http request will
have to contain or the presentation off the results we want to create when getting
resorts. The http response will contain a resort to the presentation in its body.
Former off those presentations is what media types are used for, like application
Jason. But its application Jason really sufficient enough asking the question is
answering it application. Jason tells us something about the former off the data
Jason, but not about the type Roy Fielding. The guy who called the term rest has a
pretty insightful quote on media types in relation to rest ful AP eyes. You might
remember part of this one from the overview. In the beginning of the course, Arrest
a P. I should spend almost all of its descriptive effort in defining the media
types used for representing resources and driving application state or in defining
extended relation names and or high protects enabled markup for existing standards.
Media types, the first part of the definition already answered our question. You
can hardly say that by using application Jason as media type all over the place.
That's almost all of the effort goes into defining media types. In fact, most http
AP Eyes or Web AP Eyes don't define media types at all. Rest ful AP eyes, on the
other hand, should there's quite a few scenarios that this allows. Let's start by
fixing the issue we ended up with at the end of the previous module

HATEOAS and Content Negotiation


[Autogenerated] on screen. It's part of the response from request to get altars.
You've got two fields value containing the orders and links containing self fling,
which you can see on screen. But as we've seen in the day and was in the previous
model, all darlings can be included. A swell, for example, to the previews were
Next page. The leaks are part of the resorts body. That begs the question. Is this
really the correct place to put these legs? To be able to answer that, we must take
a look back at counter negotiation. What we're actually dealing with here are
different representations off the resource, and we're mixing these up. We've called
the negotiation we asked, truly accepted her toe. Get back adjacent presentation
off the resort. So that's what we do when we ask for media type application, Jason.
But the return is a representation of the orders resource with additional semantics
dealings on top off the Jason representation of the order, so the links shouldn't
be part of the resource. When we ask for this media time, we've effectively created
another media time, which we are wrongly returning. The same applies to a single
resource By the way, adding the links to one order, even without an envelope, is
also a different media type. So by returning this response when asking for
application Jason's media type, we are breaking the self descriptive message sub
constraint, which states that each message must include enough info to know how to
pro, says the message response will have a content type, moderate value
application, Jason. And that doesn't match the content of the response. So the
consumer of the FBI doesn't know how to interpret the response, judging from that
content type. In other words, we're returning to wrong the presentation because we
don't tell the consumer how to process it. Well, that may be putting it a bit too
harsh, but we're definitely not as strict as we could be. Consumer knows it's
Jason, but it doesn't know anything about what's going to be in there. Solution is
creating a new media types, So how do we do that? There's a form of for this a
vendor specific media types. You could see an example of that on screen application
is a top level time. This is a reserve bar. First part. After that, it's fi nd the
vendor prefix. That's a reserved principal has to begin the mime type Witt. It
indicates that this is a content time that s vendor specific. It sound followed by
a customer identifier of the vendor Marvin in our example and possibly additional
values in our case refused. Hate us. And that sounds like a good one to use for us.
By requesting this media type, we are requesting the links to be included. The last
part plus Jason thousands. How to pro says the media type. It's Jason for months.
So if this new media types requested, the league should be included as they are now
part of the disorder. Presentation to consumer must know about this media type and
how to process it. If this media type isn't requested, the league's shouldn't be
included. Let's see, how we can support is with the demo

Demo - HATEOAS and Content Negotiation


[Autogenerated] in this demo will make sure that hate us. Links already turned on
Lee when the correct media types requested We're requesting application. Jason
Onley adjacent presentation off the resource should be returned and when requesting
application VND dot Marvin Don't hate us, plus Jason. The links will be included.
We're back in to get alter action on our oldest controller. This is where he ended
up in the Last model, were always returning the links. First thing we need to do is
get that, except better because our decision depends on it. To do that, we can
accept an additional parameter using two from Heather. Attribute. That attribute
tells the free work that this parameter should be bound using two requests. Others
re bossing the name off the header. That's except and we give the parameter tonight
media type. The first thing we want to do is check if a valid media type was
important. Media type. Better value is defined in two different names basis. Be
careful which one you select. It's the microsoft dot net dot http, Till Heather's
name space we need. So let's have a using statement to that. By pressing enter, we
try to part, the media type. And if that isn't successful, really turnabout
request. If it is successful, this was a valid media type, Mind you, and accepted.
It can be compromised of different media types. So if you want to support that,
you'll have to use dry parts list instead of try pars for our purposes. Let's
assume only one type is input it. Then we can use this value. Let's go down a bit
to Eric. You're early. Return the altar with legs. Let's around is with an if
statement like this. The links are only created and returned when the media type
matches application fee. A little Marvin don't hate West plus Jason. Otherwise
really turn the order without links. Let's give that a try. Let's start by sending
your request. We've already used a few times in the past getting an altar. The
accepted ER is application Jason, so they should return the altar without links and
there we go. Works is expected. I've got another request lined up here with an
accepted her of application via lee dot marvin. Don't hate us. Plus Jason, let's
send that and we get back 406 Not acceptable. What's going on? Let's have a look at
our consul output window. If you look down here, we see a warning. No output for
motor was found for content dives. Application really got Marvin Rotate West plus
Jason. And that's the issue. We don't have any output form. It was registered as
one that can handle this new media type, but we can't solve that. Let's open the
start of glass on the NBC options object we have access to and calling in. To add
controller, we find the collection of output for murders. Each of these output for
murders has supported media types collection. We can add media types like
application via needle Marvin Mojito a suppose Jason do the supported media type
collection off the output for ______. We want to handle this media type. But which
for mother is that if you look at what we change right after calling in to add
controllers, we see that we added in Newton's off Jace informers. These are the
four murders that handle Jason input and output instead of the building Jason for
murders, grease nous that they are more feature rich. They are, for example, still
required If you want to support chase and patch documents, which are a P I dust.
The issue is that these for murders are at it after we can access the NBC options.
How performances list. So if we look for a new tone soft chase and I'll put for
______ on the output for Mother's collection at that time, it won't be there, but
no worries. We can work around it. Let's get rid of this coat. We can't go figure
the NBC options afterwards as well. That's crawled out of it by calling in to
configure on the service's collection and passing through NBC options as the type
we can go figure them again. So on this conflict, objects I'll put formed his
collection. We look for an output for motor off type neutron soft Jason output for
______. That one's defining Microsoft to the SP netcord NBC dot for mothers so
that, sadly using statement by pressing enter to be able to access off type, we
have to import system. Not like so let's do that as well. If one exists, we add
application VND know Marvin Rotator s plus Jason to its support media types
collection. Note that doing this at support for this media type application wide
the other way around exists a swell. We can restrict certain actions controllers or
even the full application to certain media types. We'll cover that approach when we
need to produces and consumes attributes later on in this module. Currently, we're
going to allow, including hate US links in representation globally for all
resources. Let's give this another try. We're back in both, man, let's send this
request again. And there we go. Our links are included. Up next would be doing the
same as we just did for altars. And when creating an altar and swell, we're not
going to do that as it simply follows the same principles we just learned about.
All right, so this is already an improvement. But media types can be much more
valuable than this. Let's learn what else is possible

Tightening the Contract Between Client and Server with Vendor-specific Media Types
[Autogenerated] We've just used our first fender specific media type and
immediately saw the advantage of it. But there's more we can do these days. More
and more a p. I started using vendor specific media types. Let's take unaltered as
an example, we're currently using the order with concatenation name and age as to
return type. When getting old. We assumed that that stood a presentation most
consumers would want. But is that really the case? You could imagine that some
consumers might want the order like that, but others might want the altar with
first name, last name and date of birth fields. Those are just do the presentations
off the same altar. Yet we can't request these when we use application. Jason, our
FBI doesn't know which way presentation to return. It just knows we want it in
Jason, Former, we found the specific media types. We can't specify the exact time
we could create to render specific media types. Fear needle, Marvin the altar. Not
friendly for the friendly, formal with age and name and V indeed, old Marvin the
daughter. Don't fool for the presentation with first name, last name and date of
birth, this Titans to contract between client and server and thus makes our system
more reliable and evolve herbal. These are what are called semantic media types,
media types that tell something about semantics off the data. I what it means a
vendor specific media type can does be a semantic media type if it's used in the
way we just described. But how do we combined that then, with hate OS leaks
application via needled Marvin Potato us would give us an alter the presentation
with links and the other media types Wouldn't we could fix that by creating new
suffix. Close Jason. He's a suffix. We can add a plus. Ito s suffix like that.
Consumers can ask for the Friend Leader presentation without leads the friendly,
the presentation with links, the full representation without links or the full
representation with legs. This is something you can see in the wild from time to
time. But according to the media time definition, there should only be once off
exper media type. Next to that, only officially registered suffixes should be used.
So while the examples we just looked into will work, they do violate a few best
practices in that regard it's better to add the hate US part to the type itself. So
like that we can use this media type for the friendly. The presentation. Without
links, we can use another one for the family. The presentation with Wings, one for
the full representation without legs and, lastly, one for the Fuhrer presentation
with links. Important to know is that we should always return a default as well. I
eat when the user requests application. Jason, Let's say that that's our friendly,
the presentation without Heat, West Wings. And, of course, we also still want to
support via need dot Marvin Potato s. Well, that seems like quite a bit of work,
but it's actually not as much work as it seems that's here. We can implement that
in a Dave O

Demo - Tightening the Contract Between Client and Server with Vendor-specific Media
Types
[Autogenerated] in this demo, we'll add support for vendor specific media types
when getting an altar. Let's start by adding a class for our full old. We'd like to
take the model folder and we had a new class. Let's name it. Alter Full video. This
one contains idee first name, last name, date of birth and main categories. So just
like the entity but without the courses, let's add a mapping forties. For that, we
open the altars profile and we had a new mapping from source type and the's No
daughter to destination. Dive models don't alter ful detail. All right, let's save
that and back to our get alter action. We're already accepting a media hype and
checking whether it's fell it. We did that in the previous table, so we have a
party media type. The first thing we want to know is whether Ling should be
included for that. We have to look at the subtype without suffix. That stuff takes
that's plus Jason. So that's the part we're ignoring. Once we have that, we check
if it matches. Hate Wes, and if that's the case, we can safely create links. So we
added variable to store these links, and if we need to include them, we create him.
Then we need to check. If the full alter has been requested, we need to be able to
differentiate between the full altar and the friend. The order or application.
Jason. As these two are the default, we can simply check for the full alter part of
the media type. So with a little bit off string manipulation, we can quite easily
get to that. It's either the subtype without suffix or that same subtype without
suffix without hate us part. If that matches VND, don't Marvin the daughter, not
fool. We know we have to return unaltered. Full video. In any other case, we want
to return the friendly. Alter the presentation so the map and shape potentially
include links and return it our code from the previous day. Moist, no longer
necessary. That part is handled by the new coat. We dote. All right, let's give
that a try. Let's try getting a full order. No links included. We hit that for 06
Not acceptable ever again. That makes sense because there isn't a single output for
motor that supports this media type. We could go ahead and add global support for
this. That will work. But there's another way back to our coats. What again?
Looking at the gets alter action. A few clips ago, I mentioned that there was a way
to couple media types to specific resources. By applying to produces attributes, we
can restrict the media types and action can produce. I return. And that makes sense
for our use case, much more sense than supporting and globally. We are pretty
strict in what we want to return. We don't want to. For example, let these action
return something when say, fi nd does Marvin Look course was set us value for the
accepted. Currently, that would work if, via Little Marvin, of course, was globally
registered. So let's all of these tuitions You won't go. We applied to produce is a
tribute to our get alter action, and we passed through all the types allowed for
this action. Be careful with this, though. This is Freddie restrictive. Any type
not in this list will return a four or six all acceptable, but depending on how
strict you want to be. That's exactly what we want. A quick dip to avoid
duplication you could also apply to produces attribute that controller level or
even globally. It's just a filter so it can be added to the global filter
collection if needed. It's not applicable for the demo, but it might come in handy
in a real life project. Let's give this another try. Let's try getting a full altar
without legs. That's request. We still have lined up and there we go. There's our
full altar. If he changed the accepted her Tuvia leader ____ in the daughter. Don't
fooled off Hato s plus Jason. We should get the full alter, including legs. Let's
try that years or older, including the links. And let's try the same for the
friendly. The presentation. We try to get it without links by passing through an
except other with value application VND not Marvin the daughter, not friendly.
Bless Jason that send it. Here's our friendly. The presentation with a name and an
age instead off first name, last name and date of birth fields. And now let's try
getting it with links, and there we go. Now, if you'll remember, we should also
support application Jason and our coat does just that Let's try getting an altar
within. Accepted her application. Jason. This is a request from a previous table.
Let's send it again. And there we go. This still works. This returns to friendly
the presentation without legs. That's our default. Lastly, let's try to request
from the previous demo again. This media types simply states that we want to
include links without being too specific on the type. It should still work. Let's
give that a try, and there we go. That still works. It returns the defaulter
presentation off the order. That's the friendlier presentation, and we get links as
well. So far, so good we're not going to implement is on the altars resource. But
it's exactly the same principles that you have to follow to do that. That's it for
output. But what about import? In other words, what about allowing a consumer to
input data in different forms? Let's learn about that next

Working with Vendor-specific Media Types on Input


[Autogenerated] when inputting data, we can use vendor specific media types well by
setting them as value for the content. I Petr, what would a good to use case for
that? B. Well, I made a small mistake. It's a shame, but people die and so do
alters curently. We have a date of birth, but no date of that. What we're going to
add is the date of that field for our altars in our database. And in the future, we
want to ensure that when posting and order, this field can optionally be passed in.
We don't want to break existing implementations, though. A consumer should still be
able to pass through an altar without that field. So we should be able to import
adulteress for used to. Let's say that's valid for application. Jason and
Application via Needle Marvin Note Order for Creation, plus Jason on Altar with a
date of that would then be signified by a new media type application. Fear Needle,
Marvin, Boat, Altar for creation with date of that, plus Jason. Now, in this
example, we're just adding a field sometimes that is solved between quotation marks
by just changing the type with an added field and checking it for no values then,
of course, isn't conceptually correct anymore. And to be avoided. Moreover, it
feels take on a different meaning are already moved. That approach becomes much
harder here to being strict, improves reliability and evolve ability. Let's check
this out with the demo.

Demo - Working with Vendor-specific Media Types on Input


[Autogenerated] in this demo, we'll look into using vendor specific media types on
input. We're going to implement a use case we saw on the slide, so the first thing
to do is add the date off debt for an order on the altar entity. Here's our altered
under D that's added eight of that unknowable daytime offset date of that, thus
isn't required. Field that saved this and let's have a migration for that that
takes care of that before we forget. Let's change the way we calculate the age
that's calculated in the get current age mattered in daytime, off set extensions,
Birth ball. Let's ensure we also accept the date of that as a parameter, and I
Let's take that into account when calculating the age sweep. The date of that isn't
no. We start calculating from that date of death instead of from the current eight.
Age is then the year of the day to calculate, too. Mine is the actual daytime
offset. We're using this extension methadone, if that they to calculate to is
smaller than that, you're Inti time off set, plus the added age In years, we said H
equal to age mine as Well, this is to make sure we correctly calculate, is when the
date hasn't passed yet. So when the altar hasn't had his birdie up, lastly returned
it so we can get rid of that previous goat. Let's save this. Discovered is using
the altars profile. So let's open that alters profile. And let's make sure we
passed through the date of that when calling into that get current age method.
There we go. The next thing we need is an altar for creation. With the date of
that, we already have an altar for creation video. So that's add a new DDO and
let's name it altar for creation with data off that video. If you live from the
order for creation video and it adds a date of that there we go back to the orders
profile because we now also need mapping from an altar for creation with date of
that GTO to an altar entity. There we go. That's already it for our database and
the calculation. Now we can continue to the implementation logic. Let's have a look
at the create alternate. You find that on our oldest controller, depending on the
content I've had her value. We should either except on all for creation video or an
altar for creation with date of that video. And that's a bit of an issue. We can't
just easily do that with one minute we need an additional well, so let's add one.
Currently, this is an exact copy off to create Alter matted with a different name
for the route. A different name for the method and a different type of him put
parameters in real life situation. The body off these actions would or could
contain different code. Obviously, for our sample, this will do. But we do have to
somehow different shade between these actions, depending on the value off the
______ dive heather. And that's where action constraints come into play. These
allow us to select an action, depending on, for example, the content. I've Heather.
In other words, with such an action constrained, we won't even hit the wrong
action, meaning we can nicely separate them. So let's do that. Let's have a new
folder Action constraints that's had a new class to this folder. Well, name it
requests had her matches Media type A tribute. This is going to be our action
constrained attribute. So we wanted to inherit attributes and implement I action
constrained I actually constrained is defying the Microsoft today s peanut court on
NBC Action constraints. So let's see how to use a statement by pressing enter in a
constructor. We want to accept the request of too much and the media types that
will result in a match. We're also going to store those in the media type
collection that's defined in Microsoft to the SP Net or the NBC 0.4 murders. So
let's add a using statement by pressing enter. First thing to do in the constructor
is to check the input. We're going to need a field to store the request center to
match, and then we set that to request, said it to match. That's input it. If it's
not, no, then we need to parse the media types that result in a match. We already
have a media type collection to store them in, but we still need to check them.
This code probably looks familiar, refused this media type better value in the
beginning of the module as we remember it so well defined in Microsoft Open Apple.
Http told headers we need. So be careful when adding the using statement. All
right, so we try and parse each impotent media type. So that's the media type
parameter and the older media types parameters. If the media type checks out, we
add it to the media types collection. If it doesn't, we throw an argument
exception. That's it for the set up. Now let's implement the eye action constrained
interface. It contains an order and an except metal. The order property decides
which staged the constraint. This part off action constraints run in groups based
on the order. All of the framework provided to be matter attributes, use the same
order value so that they run in the same stage. And what we want is for dis
constrained to run in that same stage as well. And that's stage zero. The except
method returns bullion if we want. Throughout, we apply this after you two to
imagine by this constraint, it should return true and otherwise false. We want to
check if the request center to match contains one of the media types of values. So
we get the headers we can get to that fire round context or, http context. Don't
request all tellers. If none of those headers contains request set of too much, we
returned false. Otherwise, we need to parse the requested media type for that.
Create a new media type, passing through the value off the request other too much.
Lastly, we check if one of the media types in our collection matches the part.
Request media type. If it's the case, sweetie, they're untrue and otherwise false.
Let's say this and let's go back to our oldest controller. Let's start it to create
alternate. This action should stay as is, but it should now only accept
application. Jason and Application via Needle Marvin the Altar for creation, plus
Jason. As content, I've other values. For that. We use our newly created action
constraint to ensure that only when the content type matches one of these media
types this action is routed to are a tribute is defining course library though the
FBI the election constraints. So let's add a using statement by pressing enter our
newly created create alter with date of that mattered should then on Lee, be routed
to with the content. I've matches via Ledo Bar, being the daughter for creation
with date off that plus Jason, that's it for routing. But we still need to specify
which media types or actions can consume, just like there's a produces. A tribute
to restrict while in action can produce. There's a consumes attributes to constrict
while in action can consume. So this has to do with the media type for the input
for ______. That's those different from our request. Other matches media type,
which ensures routing to the action, is loud or blocked. So let's at those consumes
attributes for create alter the date of that we had it consumes, attribute,
matching that media type for our create alter action. Re at one for application.
Jason and Application VND Dope Arvin that order for creation. Plus Jason. Let's
have two break points in these actions and let's give this a try. All right, let's
give this a try. First request. We're going to send his request to create an alter.
If you look at the body, we see that no date off debt is included, and if you look
at the headers we see we're going to send it with content type of application.
Jason, there's nothing special about this. We've done this before. Let's send it
and we hit our break points in to create alternative. So far, so good. Let's
continue and there's our created altar. Now let's try sending the same request, but
with content type application V ended up Marvin not order for creation. Plus Jason.
Let's send we again hits to create alter action exactly as expected. And there we
go. Our older has been created. Now let's try creating an altar. With the date of
that, the ______ type is set to Vienna, Marvin not order for creation with data off
that plus Jason and in the body, we see that we now include a date of that. Let's
send this request And this time we hit our creative, authoritative that method.
Let's continue and there we go. Our order has been created. That's it for using
media types for input. As you can guess, media types for input and output can be
combined. You could enable the consumer to create an altar and then request one in
friendly formal orders the full time. We're not going to implement that as it's
just a combination of what we've already done in this module. We do need to talk
about one more thing, and media types come into play here. A swell version ing

Versioning in a RESTful World


[Autogenerated] when we talk about version ing, we're actually talking about
adapting to change and a P I changes what we can do with the A P. I changes. We may
be allowed to create an altar today, but we might not be tomorrow or resources
might be at it already moved. Those are functional changes. Related are changes in
business rules like in our example in the previous module, the minimum age to
reserve a seat for a course. My change. And then there's changes in resource for
presentations Sometimes feels are added. Already moved. We need to be able to adapt
to this without breaking consumers of the A P I. Adapting to change like this is
evolve ability, and that's one of the key concepts we've been talking about
throughout this module. But how do we get up to change? Well, there's different
version ING strategies used for this. Sometimes you see foraging through your eye
where the V one part is included. Another way to ______ might be true Query string
parameters and yet another way is by using a custom header. But is that really how
we should version in arrest for world? Let me quote Roy feeling once again. In
August of 2013 he lived the Kino Talk and Adobe Evolve Conference, where he was
asked how we should version rest Filippi eyes. His answer was, Don't I read that
and I thought, Well, this doesn't make sense. One of deep principle rules from
building a P I is always first in the a P. I stuff changes. We should be able to
adapt to it. He added to this by asking the question. When was the last time you
saw a version number on the website? Well, he makes a great point, but there's a
bit of an issue with this curently. How do you adapt to changing the rest ful
world? Well, change what we actually want to control when talking about version. Ng
comes in those flavors on the previous side, and we know how to tackle this. The
functionality changes hater wrestling's take care of it. If business rules change,
it's the same story. The applications that consumed the AP. I must look at the
State West links, and if they do, they will not break if one of these changes. But
what if resorts representations change fields can be added, Already moved, for
example. Well, that's still a bit of a problem. According to Mr Fielding, these
should not be version either. But to allow for something like that, we're back to
our initial problem. How can we let consumers off the A B? I know what to do. The
presentation should look like and we're over. How could we make sure these
consuming applications automatically evolve? Underrepresentation evolves. The
option to fix this, according to Mr Fielding, is the code on demand constraint.
That's the optional constraint that state that the A P I can extend client
functionality. It's a good fit for jobs group based applications, consuming
application downloads to charm a script. And it's up to the A P I to change his
JavaScript Resorts of presentations change. The JavaScript could then contain
object definitions for each of these media types. From that moment on, we would be
truly evolve herbal. But that's JavaScript. It's a different story when you need to
support different types of clients, build in different languages for public rest
ful ap eyes we might not even know about. Moreover, all of these types of
applications will almost have to be also generate on additional field would mean an
additional textbooks in the u. I. So if the resource changes well, d'you I should
adapt. That is much like how Web app works and, after all, rest was conceived for
the image of a well designed Web app in mind. The Brows of gets back a response
from the server, interprets it and shows the webpage. It fully generates the user
interface from the presentation by interpreting HTML Java script Sears, as in the
likes. So what Mr Fielding States makes sense, but more often than not, are
applications don't self generate. What we built is, well, not ready for that yet,
so it's a great idea, and it'd suit true evolve ability. But currently it's not
feasible for the majority of applications rebuilt. So for this specific part, I
prefer to divert a bit from the best practice Mr Feeling suggests. But of course,
still, adhering to the rest ful constraints what we do then well, for resorts of
presentation changes, we can use version ing on that level. It's a new type of
representations, so we create a new media type. We does virginal presentations
through media types. We could go out with friendly names like Read it or we could
do that by adding V one feet to through the media type to ensure that tine
applications don't break. We support both versions, of course, so V one can still
be used by existing maps. Envy, too, can be used when these applications are
changed. It's still according to rest constraints, so we're good to go with that.
It's time for the summary.

Summary
[Autogenerated] in the last two modules he focused on Hey, tow US and media types
Correct use of these often separate AP ICE that intend to be rest ful from truly
rest ful AP eyes. But in reality, what we really learned about was evolve ability.
These were also the modules in which we learned that building a rest ful system is
a lot different from building a standard Web A P I. As we learned a custom media
types should be used when a consumer wants to include his hate West links in the
response body, as it's a different representation of the resource. These media
types are key principle and building rest sleepy eyes. What we did up until this
module, using application Jason for a resource of presentations actually isn't
truly correct. Unaltered. A presentation with first name, last name and date of
birth is different from the presentation with name and H. These are different media
types. We shouldn't use application Jason for that. Instead, we should create
separate media types. By doing so, we're attaching semantics, I meaning to what a
client can request storybook that leads to better revolve ability and reliability,
and that then let us tow adapting to change inversion ing. We learned that we
should use hate us for changes to functionality and business rules, and that until
the gold on demand constraint is feasible, we should use version media types
building truly rest ful. FBI does take a bit of work, but the evolve ability it was
designed for this word it and we're talking system that are built to adapt to
change over years or even decades and not months. That's it for hate, Westen media
types. If used correctly, it can be a tremendous addition to an A P. I for more
constrained remains the catchable constraint. Another big one. We'll look into it
in the next few modules.

Getting Started with Caching Resources


Coming Up
[Autogenerated] in this module will get started with cashing resources. I'm Kevin
and I'll guide you through it. We've got one more constrained to cover cash
ability. Cashing is not easy. It can dramatically increase performance. But it's
also one of the first things to look at when unexplainable books seem to happen.
Http cash is considered the holy Grail of cashing. So that's when we're going to
implement who first learned about the different cash types as defined by the
standard. We'll have a look at Microsoft's response cashing middleware, and we'll
learn how it compares to that age DDP Cash standard. Lastly, we'll talk about cash
exploration and validation models and the cash control header Let's dive in.

Supporting the Cacheable Constraint


[Autogenerated] the casual, constrained states that every response should define
itself is catchable or not. So it's quite easy to a deer to dis constraint. We can
simply add, Responds Header, stating the responses and casual. And that's perfectly
Fallon. But that would make this a very short module. So instead, we're going to
see how we can ensure our HDP responses are catchable. For this will use age DDB
Cashing, which is part of the HDB standard and describe in full in our F C 7234
Let's have a look at what the Standard States as a bit of a mission. Statement on
cashing cashing would be useless if it did not significantly improve performance.
The goal of cashing in http is to eliminate the needs to send requests in many
cases and to eliminate the need to send full responses in many other cases.
Eliminating the number of requests that have to be sent reduces the number of
network ground troops required for many operations. HTTP Cash uses an exploration
mechanism for that purpose. Eliminating the needs to send full responses reduces
network bandit requirements for that validation mechanism is used. It does depend
on where the cash lifts on what exactly is reduced by a specific mechanism. We'll
get to that so we'll look into exploration and validation. But let's talk about
that cash first. Looking at it from an A P I point of view, we're working with http
and the cash is a separate component. It sits between the client application to
consumer of the A P I, which makes the requests, and the A P I itself. This cash
must accept requests from the consumer and pass them on to the A P I. It will also
receive a response messages from the A. P I, and it will store responses that are
deemed catchable and forward them to the consuming application. If the same
responses requested again, the cash can send the cash response so we can look at
the cash as the middleman of the request response communication between the
consuming application and the A P I. Well, that's interesting, but it's all so
confusing. This would mean that a request from a consumer still has to be sent to
the server. Sure, Akash response can be served up from gosh so we don't necessarily
hit our a P. I code anymore, but it's still a request plus response that sent over
the wire Well, this confusion comes from the fact that in HDTV cash, there's
actually tree types of cash. Let's look into those.

Cache Types
[Autogenerated] So in. Http there are tree cash types. One is the client cash or
browser cache. It lives on the set of the client application. A browser is an http
clients, but we can extrapolate that if for building, for example, mobile client
application with salmon. That client application, which communicates with the A p I
threw an http Klein instance, will often have a private cash. It's called private
because the resort has can be shared with anyone else. They're kept on the client
for each consuming instance. So good examples are a cash on your mobile device, but
also a cash in local storage. For an angler app. The second type is the Gate three
cash. This is a shared cash to resources. It caches are shared across different
applications. This type of guys, she was on the server side. All the names for
this, our reverse proxy caches or even http accelerators. This is does the cash
time that's often putting from the baby eyes. The third type is the proxy cash.
It's also a shared cash, but it doesn't leave after consuming side nor outside of
the FBI. It lives on the network. They're often used by large corporations and ice
piece to serve thousands of users. If you ever had to change your browser settings
and input a proxy address, well, you've used one of these regard. Focus on this
last well as it's out of our control. Most of the time combinations are used a
private kasher consuming side combined with the gateway cash that server side and
maybe even a proxy in between, depending on whether or not the response is casual
and where it is allowed to be cashed, we might are back and right up to the
database. We might hit a proxy or gateway cash without having to communicate with
our database. Or we might only hit a private client side cash A living in
communication between client and server completely. Microsoft has a piece off
middleware for the shared gateway type cash response. Cashing a tribute Emily
where? Let's look into that

Response Cache Attribute and Middleware


[Autogenerated] so to support cashing, we essentially need two things. First thing
we need is a way to state for each resorts, whether or not it's casual. That song
by response Header There are various factors to consider. Ever look into those, but
most often used? When is the cash control heather? An example? Might be a cash
control heather with a max age set to 120. This states that response must only be
cashed for 120 seconds to achieve that response. Cash attribute issues, but all
that does is set to response. Header. That doesn't mean the response is actually
cashed. We still need a place where it is cashed a cash store, as we just learned.
There's different types of that at client level, server level and a proxy level.
Microsoft provides a cash store week, an added level of our FBI by adding to
response cashing mill where to our request pipeline. That mill, where is
responsible for storing catchable responses and serving them a permit store.
Combining these two thirst leads to what we need. Let's have a look at how to do
that with a table

Demo - Adding Cache Headers to the Response


[Autogenerated] in this demo, we'll learn how to use response cash attribute to
control the cash control header on a response message. We're looking at the courses
controller. Let's say we want to make a course catchable. Let's go down to the get
course for alter action here we had response. Guys attribute, and we set the
duration to 120 seconds. As you can see, there's a lot more properties we can set
to control that header. We look into those later on. For now, we should do the
trick. Let's give this a try. I've got a request lined up here to get one specific
course. Let's send this request. Here's our course. Let's have a look at the
response headers. There we go. Akash control header, the max said, she said, to 120
seconds, meaning that this response can be cashed for two minutes. Public refers to
the location where it can be cashed if that value is public. This means this
response can be cashed by boat shared and private caches. So it's over level, proxy
level or client level. If it would have had a value of private, it can only be
cashed by private cash is so at client level. What we want to do is send the
request again. But have it served up from a cash so we shouldn't hit the get course
for alter action? Let's have a break point there to check for that. Before we send
this request, we must check something postman will by defaults and no cash header.
And we obviously don't want that as that'll result in the response not being served
from our cash. So let's open postman settings and make sure that sent no cash
header is set to off. That's already okay on my machine. So we're good to go. Let's
send that request again. We still hit our break point. In other words, even though
the response of our previous request was catchable for two minutes, it wasn't
actually cashed anywhere. We need a cash store for that. Let's add one in the next
evil

Demo - Adding a Cache Store with the ResponseCaching Middleware


[Autogenerated] in this demo will add a cash store for that. We want to open the
start of class in the configure Service's methods we want to call into at response
cashing. This ensures that the necessary service's are registered on the container.
Now let's go down to configure Met it here. We want to call into use response
cashing toe at mill. Where to request pipeline. Make sure this is added before the
calls into use rowdy and use and points. We want to ensure that a cash deal where
can serve something up before the rest of the NBC logic is routed to or execute.
Let's give that a try. Let's send a request to get a course again. First time we
hit our break point. So far, so good. Let's continue. Let's have a look at the
headers. We get it back, including a cash control header. Let's immediately send
this again. We didn't hit our break point. Our responses to us served up from the
cash. If you look at the consul, we know we can indeed see that response. Waas
cashed and below that that it was served up from the cash. If you look at the
response headers. We now also notice an H heather. And that's something you, this
states that age. The response has been in the cash in seconds. Let's send that
request again. The age changes. Our response is now 68 seconds old. Now let's wait
a little bit until 120 seconds have passed. Let's send it again, and there we go
hit our break point again. That makes sense because the cash response went still.
So far, so good. Now you might have seen the cash control directive being used for
a request instead of response. That's the file of Jews case. Both clients, true
requests and servers through responses can partially control cashing rules. We'll
look into these later on in this module. First, let's go over something else.
Often, the cashing rules for different resources are the same. 120 seconds for
accords. But also for a set, of course, is what an altar, for example, cash
profiles can help with that. Let's continue with the next table

Demo - Using Cache Profiles to Apply the Same Rules to Different Resources
[Autogenerated] in this demo will learn how to use cash profiles so we can easily
apply the same rules to different resources. We're looking at the start up costs ad
controllers except a set of action. And on that set of action, there's a list of
cash profiles by calling Add on its we can have a new one. Cash profiles is
actually a dictionary, so we need to give it a key. Let's say, 240 seconds cash
profile As value we add to the actual cash profile, we give the duration of 240
seconds double of what we had before. That's a this. Let's continue to the courses
controller. Cash profiles can be applied to the response cash attributes and that
can be used at control or an action level. So let's apply our cash profile at
controller level. We apply a cash profile by setting the cash profile name to the
key. We gave the cash profile in the Cash profile dictionary as response Cash
attributes at action level over I toes at controlled level. They should mean that
when we get one specific course, we should still see a maximum age off 120 seconds.
However, when we get the courses, we should see 240 seconds that's built. Alice.
Give this a try. Let's send that request to get a course again. And if you look at
the cash control heather, we see a max age of 420. Now let's get the courses. And
if you look at the response headers, we see a maximum age off 240 seconds, as
expected. So that's pretty cool, right? But how does it actually work? I What are
the mechanisms that decide on whether something is served up from a cash store or
not? Let's have a look at the exploitation and validation models.

Expiration Model
[Autogenerated] the expiration model is away for a server to say how long requested
resource so response message is considered fresh. Akash Condensed store this
response so subsequent requests are served from the cash as long as it's still
fresh for this dude responds headed for used. The expired headed is the simplest
well, it contains an http date stating at what time responds expires, but that has
a potential issue. The clocks must be synchronized between cash and server. It also
offers little control over what types of responses can be cashed when and where
it's been superseded by the Cash Control header, which addresses these limitations.
In the example, you can see Akash Control Head of values Public Max H equals 60.
This response headed contains two directives. Max, age and public. As we learned
during the demo Max Age, States response can be cashed for 60 seconds. It also
means that the clock sink is no longer an issue to recapitulate public states. That
it can be cashed by both shared and private cash is so the server can decide on
whether or not the responses even allowed to be cashed by a gateway. A proxy cash
those are shared or at all, for that matter, disquiet a few possible directives
next to public and max age. You can find those at link on screen. They're divided
between directives that can be sent in a request so kind can decide on some
explanation related values and directives that can be sent in response so the
server can decide. We will look into these later all, as some have to do with
expiration and others with validation. So we have to cover that. First, let's have
a look at how this exploration model works. Imagine we have a client application,
consumer of our FBI, Akash shared or privates and our FBI. The back end. The
application sent a request to get the orders. This request. It's the cash. There's
no cash version of the response available. So the cash forwards the request to the
A p I. Or maybe I should then return the response, including cash control. Heather
that, in case of our example, states that the response will stay fresh for 1800
seconds or half an hour. That hits the cash Egan and the cash then forwards it to
the consuming application. But at the same time Stores copy off this response 10
minutes later. Our absence. A request to the altars resource. Again, we get the
cash, and this time the cash is a response. It hasn't expired. It sends Baghdad
response, including an age header in our case at ages 10 minutes or 600 seconds. A
request to the back and distrust. Eliminate only when the cached version reaches
expiration time, which means it becomes still the cash will hit the back end again.
If this cash is a private cash like one that lives in local storage for the
Wrangler up or on a mobile device for a mobile app, that's where it stops. But if
we assume that the cash is a shared cash leaving on the server, for example, it's a
bit different eminence Later, subsequent requests from another instance of our
client application or another client application that consumes or a P I to a P. I
ordered it will hit that cash and assuming the response hasn't expired, it will
serve that up from the cash this time within each other of 20 minutes or 1200
seconds. So there's again no communication without a P I if it's a private cash
subsequent request, save bandwidth and reduce requests to the A P I as long as the
responses and expired. We don't need to server anymore for requests coming from the
same client instance. But of course, when different clients send the same request
they still hit are back, and they all have their own private cash. If it's a shared
cash, subsequent requests don't save band with between the cash in our a B I, but
it does drastically eliminate requests to R A P. I imagine there's thousands of
simultaneous consumers over a P I. The 1st 1 It's the A P I. All the other ones hit
the cash, which also means a lot less code has to be executed. The number of times
the databases to be accessed goes down drastically and so on. This is a pretty good
reason to combine a client, cash and a shared cash. The expiration Wallace nicely
supported by what refused about the Lao response cash attributes and response
cashing little where, but looking at exploration like this is typically only good
for content that's quite static images, webpages, master data and so on. So it's
actually not that could've fit for a P I psych hours off which the data can
dynamically and often change, even altered, is added by one of our 1000 consuming
applications. The altars response that's cashed isn't correct anymore. Worst case.
With an explanation of 30 minutes, we end up with as good as half an hour of
invalid data, and that's what the validation model takes care of. Let's have a
look.

Validation Model
[Autogenerated] validation issues to validate the freshness of a response that's
been cashed when a cash has a stale entry that it would like to use is a response
to a client's request. It first has to check with the origin server or possibly an
intermediate cash with a fresh response to see if it's cashed. Entry is still
usable to be able to validate, we need something to well validate against, and
that's a validator. Thes validators are used to check if they represent the same or
different responses, and that's a combination of feathers and body. There's two
types of validators strong validators and weak validators. A strong validated
changes if the body or headers off the response change. The typical example of such
a validator is an attack or ended. The deck sent true the feedback responses. So I
need Act is an opaque identify. A signed by a Web server to a specific version of a
resource. Strong validators can be used in any context with cashing, but also for
concurrency checks with updating resources as well. Learn later on in the scores a
week. Validator doesn't always change when the resource changes. It's up to the
server to decide when a change is warranted. For example, on Lee change on
significant changes and not one less significant aspects change. A typical example
is the last modified response. Heather containing the time when the resorts was
lost. Mollified. These are implicitly week. We've got a possible one second gap.
Now it is possible to make this strong by adhering to a set of rules, like an
additional date value on cash gentry. That's at least 60 seconds after the last
modified eight amongst others. But that would lead us too far. So let's treat the's
s weak. But even then, the clocks must be synchronized. So it's all for the same
issues as the expire center, which is why I e tax are better options. And there's
something like Wiki attack us. Well, when it's post fixed with W forward Slash,
it's treated as being weak. It's up to the server to decide this when an end of the
attack is in this former. It doesn't necessarily change if the response changes
week. Validators can only be used when an equivalent resources good enough, but
equality isn't required. I you don't always need the most recent first simple get
requests for cashing, for example, are allowed. They can be even more efficient.
Even equivalent version would be okay for a client. But anything else isn't. We
cannot use these if we need to be sure that different versions are equal. Nor for
concurrency checking. In other words, in case of a resource we can get a swell as
update week back is a bad idea. The HDB standard advises to send boat attack and
last modified headers if possible. This immediately poses a problem for us. The
response. Cashing attributes refused up until now does not support E tax, so we
cannot use the best practice when working with the attribute in. The next model
will learn about different approach that does allow working with the tax. For now,
let's have a look at how this validation model works, he began. Got a client
application consumer of our FBI, Akash shared or private and our FBI the back end.
The application sends a request to get the altars to request chits to cash. There's
no cast first of the response available, so the cash forwards request to our a p I.
Our FBI returns response. It includes an e Tak and lost modified header that's sent
to the cash again. Which forwards? It's too consuming application, but at the same
time stores a copy off this response. After that, our absence request to the altars
results again reminisce. Later we hit the cash, but we can't be sure that response
has been cashed is still fresh. There are no cash control headers to check for this
in our example. So the cash has to check this with the server, the A p I. It does
this by adding request headers if no match said to the e tak value and if modified,
since which is set to the last mollified value off the cash response. These make
this request conditional Serve receives this request and it checks thes headers
against validators. It holds or generates for that request. If this checks out, the
server does not have to generate a response. It sends back a trio for not
mollified, after which the cash can return the cash response with the original last
modified header. If it supports, last modified. If the resource has been modified,
the AP, I will, of course, have to generate a new response If this cash is a
private cash, that's again where it stops. Let's assume the cash is a shared cash,
a subsequent request ____ minutes later from another instance of our client
application or on other client application that consumes what a P I will hit that
cash. The cash will set if modified, since Heather, to the last mollified value of
the cache response and if no match to the attack value if it's still checks out,
response still does not have to be generated. In other words, with validation, the
same response only has to be generated ones. If it's a private cash, subsequent
requests save bandwidth. We have to communicate with the A P I, but we don't need
to send over the full response from the A P I only a trio for not mollified
responses to see if it's a shared cash. Subsequent requests don't save band with
between the cash and the blind, but it does save battles with between the cash in
the A P I. As the server doesn't have to regenerate responsive, it's still valid,
so it doesn't have to send over a responsibility to the cash. In contrast to the
exploration model. The validation model is not something that's correctly supported
by the response, cash attribute and response cashing will wear. But don't worry.
We'll look into a solution in the next module. So two different strategies to
different uses more often than not, exploration and validation or combined. Let's
have a look at what that looks like. And let's immediately make a separation
between private and shared caches that start with the private cash. We've got a
response to the orders resource cash. It has a gash control header for explanation
checks and the last mollified and eat accounted for validation chicks, a new
request descent. And as long as the response hasn't expired, the cast response can
be used. This reduces communication with the A P I, including regenerating
responses, and it reduces vantage requirements. We don't even hit the A P I. Once
it expires. We do hit e a P I. If he only have expiration checks, this means the
AP. I would have to regenerate response. But with the validation checks we can
potentially avoid is because it's not because of response is still there. It's
invalid. The A P I checks the validators and If the response is still valid, it
sends back it for you or for not mollified bad. With usage and response
generations, there's potentially reduced even more because even expired response
doesn't necessarily result in the response body. If the cash is shared, the cash
responses used as long as it hasn't expired. This doesn't result in bandit
reduction between client and cash, but it does result in bandit reduction between
cash and a P I, and dramatically reduces the amount of requests to the A P I a lot
more than a private cash. As this one is shared across potentially unlimited client
instances, it responds, expires. The cash must communicate with the A p I. But
here, us well, that doesn't mean the response has to be regenerated. If elevation
checks out, a trio for not mollify descend to the cash without responsibility. That
potentially reduces bandwidth usage between cash in a B I and responsibly
generation. The new response must still be sent to the client from the cash, of
course, combined these to a private cash for each client instance and a shared cash
at server level, and we reach the holy Grail of cash in That's it for the
exploitation of validation Muggles. There's one more thing to cover before we go
into the next model to learn how to work with the validation model and e tax. As we
learned a bit earlier. There's quite a few cash control directives available that
control cashing Bo that request side and response side. Let's have a look at those.

Exploring Cache-control Directives


[Autogenerated] Let's start with the response. Cash control directives. They're
what we've been seeing on. The slides won't allow sets by the server the first to
have to do with how long your response could be considered. Fresh max Age defines
the maximum age after which responds expires in seconds. S Max age overrides the
max age value for shared caches, so your response can expire differently in a
private cash versus in a shared cash. Then we have to that relate to cache location
public in the case that the response may be cashed by any cash, private or shared
private indicates that all or part of the response messages intended for a single
user and must not be cashed by a shared cash and under street that relate to
validation. No cash indicates that the response should not be used for subsequent
requests without successfully validation with the origin server, two more directors
have to do with that must re validate and proximity validate. We must re validate
the server can state that if response becomes stale, I If it's expired, then
revalidation has to happen. This is to allow the server to 43 validation by the
cash even if the client has decided that still responses are okay and proxy re
validate is exactly the same. US must re validate, but it doesn't apply to private
user agent cash is like a browser cache. Lastly, there's no store and no transform.
No store is available at client level a swell and states that the cash must not
store any part of the message. It's mostly used for confidentiality reasons. No
transform states at the cash shouldn't convert the media type of response body. Now
all of these are decided on my server, but the client can override some of these
settings or other use the same directives to tell the cash or server. While it is
willing to accept Max, Age indicates that the client is willing to accept response
whose age is no greater than the specified time in seconds mean fresh indicates
that the client is willing to accept response. Who's freshness? Lifetime is no less
than its current age, plus the specified time in seconds. In other words, this
means that the client wants response that will still be fresh for atleast the
specified number of seconds, and Max Dale indicates that the client is willing to
accept a response that has exceeded its expiration time. This is the one must re
validate into response reacts against. There's only one directive related to
validation, and that is no cash directive stating that response to this request
should not be used for subsequent requests without successfully validation with the
origin server. No story and I'll transform are the same as 40 spawns headers.
There's only one new one only if gashed. This states that the client wants a cash
to return on Lee. Those responses, and it currently has stored and not reload, re
validate with the origin server. This one is typically used when there is a very
poor network connection. These are already pretty advanced directives and options
in a lot of cases were quite okay with Max. Age and public or private in the next
model will dive deeper into cashing, dying for to somebody

Summary
[Autogenerated] we started learning about cashing in this module. One of the rest
constraints is that each response must state whether or not it can be cashed. We
looked into the HDP cashing standards, and that was quite a lot of information.
Cashing really isn't a simple subject, but the important parts to remember our that
the cash itself can be private or shared and depending on the type of model, can
reduce bandwith requirements and or network round trips. Those models are the
exploration and validation models. We use the exploitation model to allow the
server to state how long response is considered. Fresh for that use the cash
control header. The validation model is used to validate the freshness over
responds that's being cashed. It does this with the help off. Strong validators
likey tax or weak validators like lost modified dates or wiki tax response. Cashing
attribute is used to control the cash control headers on the response message. The
Response Cashing mill, where acts as a cash store. It's this component that
effectively stores the responses and potentially serve them up from the cash. But
their attributes limitations. It cannot generate strong validators like an attack
which limits. What we can do with it and the cash store has some limitations as
well in the next module will solve these issues.

Supporting HTTP Cache for ASP.NET Core APIs


Coming Up
[Autogenerated] eat acts are strong validators that improve the reliability of the
cash validation model. In this model, you'll learn how to use those amongst other
things. I'm Kevin, and I'll guide you through it. We learned that the response
cashing middleware isn't bad, but it also has its shortcomings in this module will
learn how to circumvent those by learning how to work with E tax. We learn how to
do that with global configuration and resorts level configuration. We'll also look
into cash stores and content delivery networks and cash invalidation. All of this
will lead to full support for http cash for our A P I.

Supporting ETags
[Autogenerated] as we learned the previous model. The validation model requires
validator dates are weak validators e tax or strong validators. Such a strong
validators preferred over the weak. One response cash attributes doesn't generate
those. So we need another component that will to make our lives a bit easier. I
created such a component Marvin, not casual headers you can find. Don't get up and
you get It's a piece of a Speedo net. Core Middle. Where, that adds HTTP cash
handers. Two responses, like cash control, expires E tak and last modified. It also
implements cash exploration and validation models. Just as we learned in the
previous model. It can be used to ensure caches correctly cash responses and or to
implement concurrency for as based AP ice. Using e tax concurrency is covered in
the next model. It's important to know that the military itself does not store
responses. I wanted to create something lightweight that could easily be plucked
into the request by plan for just one purpose, correctly generating these headers
so Akash can check for exploration and returning a trio for not modified response
message and preconditions and potentially returning for 12 Precondition failed
response the last one is often used for computers he checks. Let's start by adding
it to a project to generate e tax.

Demo - Adding Support for Generating ETags


[Autogenerated] in this day more, We'll add support for generating it. Dex. First
thing we'll need to do It's at the middle. Where to generate ese. So let's open a
new good dialogue. We want to look for Marvin, both casual Heather's that's had the
latest version. That's version, for we're in the start of class Unico Figure
Service's method. Here we should call at http cash headers to add service is used
by the middle. Where to the container. This is also where we can configure options
for how the headers are generated. We'll look into that, but for now, we'll leave
that the defaults that's called out of it reconfigure method. Here we want to add
the middle where to request pipeline, the order in which we add middle where is
important. You want to add this middle where before the controller middleware, as
in some cases, this middleware must ensure that request pipeline doesn't continue
to that, for example, when validating that response is still valid even after it
has expired. In that case, trio for not modified should be returned and response,
but he should not be regenerated. In other words, in that case, the headers mill
where must stop that middle, where from executing next to that? It should also be
added after the cash store. So after use response cashing when an item can be
served from the cash. The e tag generating villa where shouldn't be executed? Well,
______ by getting a course for an old. But currently we still every response cash
attributes apply to that action. Let's comment it out, and let's also comment out
response. Cash attribute at controller level. All headers will tell to be generated
by the Marvin the Castle Header Smilla, where we don't need these response. Cash
attributes anymore that's build a run were imposed them. This is that request from
the previous model to get one specific course. Let's send it. We get back with his
bones. Let's have a look at the headers. We see a cash control Heather has been
added, stating this response can be cashed by boat shared and private caches, and
it's valid for 60 seconds or one minute. The expires had also reflects this. It
expires while minute from now, so boat headed are at it. But as we learned, using
the cash control header is advised. So that's what we'll use next to that
validation, Aly that Heather's have been added a swell. A strong attack has been
generated, and the last modified date, which is the current aid, has been added as
well. Same logic applies here. We learned that using the E tak is advised overusing
the last mollified eight. So that's what we'll do. How it acts should be generated
isn't part of the standard. It's up to the server to us to decide on this, and that
makes sense. And it's only us who can decide when a response should be considered
equal or equivalent by default. This middleware takes to request part except and
accept language. Request said it into account and the response body. That means
that when an update to resource happens to generated e deck will be different.
That'll come in handy later. If that's not sufficient for your use case, you can
inject your own service to generate heat acts if you wish. If we look at the
console out between, though, we see that a lot of information gets out. Put it like
that. You can easily see what's going on. Let's send this request again. More than
60 seconds have passed, so we don't see an age response header. Let's try it again.
And there we go. Here's that a cheddar that already leads us to thinking that this
response is probably served up from the cash. Let's have a look at the guns. All I
would put again and indeed Microsoft Response cashing Miller. Where served us up
from the cash. So far, so good. Let's learn how he can configure exploration and
validation model options.
Demo - Global Cache Header Configuration
[Autogenerated] In this demo, we'll learn how to configure cash at its globally.
The options are divided into two parts. One for expiration model related
configuration one for validation model related stuff. We'll start with the
explanation model options. We're looking at the ad http. Cash out of statement.
Income for your service is if you look at what we can pass. True, we see there's
quite a few options we see. We can inject a custom date parts or a custom validator
value store, custom eat AC generator and so on. These options allow us to highly
configured how the component behaves. If the default E tag generation isn't to your
liking, you can provide your own. If you want to provide your own store, for
example, to use with readies, you can do that as well, and so on. Going into all of
these would lead us too far. The default implementations are okay. We're interested
in the explanation model options at this moment. For that, we can pass through an
exploration model options function. So let's do that. Setting these controls the
cash control header, for example. That's at the max age to 60. That's one minute
and the guy's location to private. Now let's give this a try. Let's end this
request and it's looking. Response Headers. The cash control heather now states
that this responses catchable for 60 seconds and shouldn't be stored in a public
cash. Now, as you remember, the response Cash store is a public cash. So let's have
a look at what happened in the console out what we know. We see a message from the
response cashing, well aware Response could not be cashed for this request. In
other words, the middle, where inspected the headers, noticed the cache location
was set to private and correctly didn't start it. Let's have a look at the
validation model options next to set that up. We passed through in action as well.
Akash Control directive related to validation. That's often added, ISS must re
validate. We learned that that tells the cash that if a response becomes stale,
revalidation has to happen. So we said he too true, and let's give it a try. Let's
send this request and there's our most revalidated directive. Now the response
cashing mill, where doesn't correctly implement the validation marble, So later on
in the courts will look into alternatives. So this is as far as we can go with this
for the moment. By the way, all of this configuration applies globally. That's send
request to get all the courses just to check. Let's have a look at the response
headers, and there they are. But global configuration only gets us so far. Often
you want to configure these headers and directives that resource level. In other
words, on the action, Let's have a look.

Demo - Resource-level Cache Header Configuration


[Autogenerated] in this demo, we'll learn how to configure cashing at resorts
level. We're looking at the get course for alter action on the courses controller.
There's two different attributes we can apply here. Let's start with http. Cash
expiration. It's the fire any more of a North Castle Heather's. So let's add using
statement by pressing. Enter these attributes, as you can guess from the name.
Allow setting expiration model related options we have globally, said the cache
location to private. So for the demo, we're going to set it too public for this
resource. We'll also set the max age to 1000. Likewise, attributes exists for the
validation model related options. HTTP Cash validation for the day Mo will set must
re validate back to false. Let's give this a try. Let's try getting a single
course. There we go. Location is public, Max said she said to 1000 and must re
validate. Isn't there anymore just to check? Let's get the courses resorts here.
The global options are still applied. These attributes can also be applied that
control our level. Let's do that. Let's set the cache location too public for all
courses, related resources and most revalidated back to true. Let's give this a
try. Let's try getting one specific course. The cash control value is exactly the
same as before. That makes sense. Actual level attributes override controller level
attributes. Now let's try getting the courses again. This time the location is back
to public, so controller level configuration overwrites global configuration. So
with these attributes, you can implement really granular cashing strategy. There's
one more thing we have to look into. Devotee had us.
Demo - Dealing with Varying Response Representations
[Autogenerated] more often than not, the presentations off resources can vary
depending on one or more requests. Others think about requesting an XML version
over the source by setting the accepted through Application XML and adjacent
version of the same resort. By setting that harder to application, Jason Akash
should know about this otherwise cached version. And XML might be served up from
the cash to a user that requested Jason. Let's send requests to get one course
again. We're looking at response Heller's here. There's three headers set as
Freddie value except except language and accepting coating. This is the default.
This means that if the except Except language or accept goading headers off a new
request to the same resource, you or I are different from what those had her values
were. For the cash version, the cast first shouldn't be served. That's justice.
Let's send this request again with an except Teller of application. Jason. Just as
we've been doing all along, we again see an age response header. This responses
does been served up from the cash. Now let's try sending that same request, but
within accepted our value off application XML. And there we go. There's no age
here. This response is not served up from the cash. Also, if you look at the body,
we see that we effectively get back an externality presentation. By the way, this
does not mean that the chase in response was over it. And let's get that one again.
Here's our response body. And if you look at the age, we see that it has reached an
age of 335 seconds. That's definitely longer ago than when we got The X amount of
presentation to Jason. Responses does still served up from the cash, which means
the cash cure of the holds two different representations, while the next, well, one
in Jason. Often the default fatty headers are sufficient. But if you ever need to
change them, the very had her value can be set on the validation options globally
or fire http cash validation attribute With that, we've already learned a lot about
fine tuning or configuration to match our needs. With all of this in place, it's
time to check out what thes e tax can help. It

Demo - ETags and the Validation Model


[Autogenerated] we now have made aware that generates e tax in this demo, we'll see
how the validation model works with those. I restarted the application so the gas
story is empty. Let's send that request together course again. Let's look at the
headers. So we get back to response with the response that we'd expect if the
response is stale. We learned that Akash must validate it, preferably using. It
acts. So what we have to do as we learned in the previous module, it's at that e
tak value as the if no match Heather. Let's do that. So we add a new request
center. We name it if no match every passed through the Eater and we get back a
trio four not modified. If you look at the council out between no, it's the cash
store that served up their response. So even though to response cash, attribute
calm, generate e tax response. Cashing store does know how to interpret them and
how to return in three or four. This is good for performance, but there's an issue
with this. As we learned it's up to the cash to send requests to our application to
validate its cast response. It's us the cash that needs to set that, if no match
other and check with the origin server. In other words, our application. It's then
up to our application to potentially return that three or four not mollified and up
to the cash to respond by potentially returning the cash response that's different
from what we just did in our example. It was declined Postman that passed through
that. Heather No, all caches are implemented to say, nor do they all correctly
implement a validation model. Microsoft's response Cash is an example of that. It's
good for simple use cases that only deal with exploration. But once validation
comes into play, it's not a good choice that set or application does correctly.
Respond. The Marvin, the castle headed Smilla. Where takes care of that? Let's come
on out the response. Cashing middleware so we can run through it. By doing this, we
don't have a cash toward anymore at level of our application. Let's run this. Let's
send that request to get a court again without an if no matches, so we're starting
from scratch. We get back to response, which responds. Heather Sweet expect. Here's
our attack. We're now going to mimic what the correct cash store should do. We're
again going to add this attack as the if no match value. It's still the same e
deck. Our resource hasn't changed. Let's send this and we get back a trio for not
modified as we learned on the slides. This tells the cash that it can still use the
cash response so the body doesn't have to be regenerated again. Improving
performance. Now let's update at court by sending a put request. I've got one lined
up here. Let's send it. We get back to afford oh content. So far, so good. That
means that response. What? Yes, now be modified. Now let's send that get request
again with same attack. As if no match her this time. Validation should fail. The
eat eggs don't match any more as a new e tak has been generated when we send to put
request. And as we see, we don't get back into your four not modified. Instead,
response gets regenerated. We see it as a new e tak and there is no age value. So
this wasn't served up from cash or anything. This is how the validation model
works. That also means the response. Catching middleware isn't a great cash store
for anything but simple use cases. But what are the alternatives, then? Let's have
a look.

Cache Stores and Content Delivery Networks


[Autogenerated] as is probably clear by now through http, CASHING isn't a simple
subject and not all cash stores behave as you might expect. In fact, in real life,
most cash stores are in just a piece of metal were like Microsoft Response cash
anywhere. They are actually full blown cash servers that offer required deep
knowledge of how to configure them more on that in a few minutes. Let's start with
private caches. A private cash, as we learned previously, lives on the client.
You're out of school for discord. As we're working on the server, we're not
building a client application yet. If you are building client side applications in
dot net core like a salmon up or a W P F up, you'll probably need one of these. A
good example is cash cow dead client. Shared caches are gay tree or proxy gashes.
As mentioned, these are often full blown service. You place right in front of your
A P I. A few household names or varnish, Abashidze traffic server and script, but
their shoulders as well. Each one of these correctly implements http cash
standards. Both the exploration of validation models combined this with response
cash a tribute from the previous module. If you only need the exploration model or
with Marvin the Castle headers, if you need expiration and validation and you're
good to go. But setting up such a cash server isn't revealed. There's another
option. A CD en Aura content delivery network. That's a system of distributed
servers, a network that deliver pages and all the Web content to the user based on
the geographical location, off the user, the origin of the webpage and the content
Livery server. Simply put, it's a network of http proxy servers geographically
distributed that speed up requests and related responses by ensuring those requests
a route to the server closest to where you are. We don't notice it anymore, but a
lot, if not most, of the Internet runs on various CD ence. It's the CD ends than
ensure popular sides can load fast anywhere in the world. But being close to the
user is just one of the things they do. That alone wouldn't speed up to request
response cycle us much next to proximity CD ence. Also extensively use cashing http
cash to be precise. In fact, most of them will use gosh servers like the ones we
just learned about. The good thing is that using such a CD at means we no longer
have to go to the often difficult set up of a casher. Instead, they're provided out
of the box and can often be configured fire. Simple user interface. A few examples
are as your CD in Cloudflare and aka my At this advantage is obviously cost. If you
expect to cash a lot of responses, expect to pay for it. The cash service. We
talked about our offer open source and free to use. So if I can offer a piece of
advice, do not implement a cash stored in application level. Just ensure that
you're a P. I can return cash control headers and supports expiration and
validation models. Oh, well implemented cash store will correctly react to those.
In other words, we're ____. As far as our FBI is concerned. For such a cash store,
use one of the cash service we just talked about or make your life easier and use a
content delivery network. The last piece of the puzzle is cash invalidation. Let's
check that out
Cache Invalidation
[Autogenerated] cash invalidation essentially means wiping a response from the cash
because you know it is the correct version anymore. A lot of this process happens,
automatically responds, is invalidated when it becomes stale. For example, next to
that, we've already seen how it acts. Help with this in the tag table. When a
resort is updated, the DAC changes, which means the validation model, ensure that a
cash will return the correct new version. But sometimes resorts manipulation has an
effect or related resources. Take the courses resorts, for example. A list, of
course, is if a put statement is sent to one course that one course will get a new
E Tak. But the courses resource doesn't automatically change if the course you
updated is one off. The courses in return course has been fetching the courses.
Resource the courses resource is out of date. Same goes for the leading or creating
a course. That, too, might have an effect on the course is resource. Automating.
Something like that isn't trivial. It's often a manual process or a matter of
implementing rules for related resources. This, too, is something seedy ends can
help it. In fact, if you read through their documentation, you'll notice they often
pride themselves on allowing you to wipe something from their cash instantly, often
fire weapon, be I sometimes even by providing and easy to use as decay. So if you
need functionality like that, see, the ends are a good option. Most cash servers
also offered his option, and with that, let's have a look at this module somebody.

Summary
[Autogenerated] this model was focused on the validation model off the HDP Kashtan.
For that, the best option is to use a strong validator like an attack. We added
Marvin, not casual headers to our FBI so eat ex can be generated By doing so. We
ended up with an A p I that fully supports http cash, which means it correctly
generates Heather's validators and implements expiration and validation models so
it can correctly respond when Akash sends a request. But we didn't have a cash
story yet. Response. Cashing Delaware isn't a good option for anything but trivial
cases. Shared cash stores are seldom something that you'd implement that
application level. They are full blown cash servers in their own right. Good
options are varnish, Apache traffics over or squid. Another option is using a seedy
end, which already implements one of those shared caches. Both of these often
support manual cashing validation, either via an A p I or by allowing you to input
rules for invalidation next to being used for validating Akash item. There's
another interesting use case for e tax dealing with concurrency. That's what we
learn about in the next model. The last one off the course

Supporting Concurrency
Coming Up
[Autogenerated] How can we ensure that when two people are working on the same
resource? An update of the results by the first person no longer over rights to
change is the second person made. In the meantime, that's what we're going to deal
with in this module supporting concurrency. I'm Kevin and I'll guide you through
it. This model is all about concurrency. We'll start by looking into an example of
how we can support concurrence in arrest for world afterwards will dive into a demo
in which will again use E tax to correctly support us. Let's dive in.

Supporting Concurrency in a RESTful World


[Autogenerated] Let's start with an example, say to users. Kevin and Sam are
working on a specific resource at the same dye. For example, they're working on the
same altar. They are kind. Instance well in client instance to as their boat
running the application on their own machines. Giving gets the altar and a bit
after that spread gets to save altar. Sven edits the order and issues a put
request. The altar has been updated. Now Kevin, who is finally done editing issues
of put requests a swell. At this moment, Spence changes are lost. That's a problem.
I'm guessing this is a familiar concept for most of you. Issues like these
concurrent updates are handled with the concurrency strategy. Pessimistic or
optimistic? Concurrency control. Pessimistic. Concurrency control implies that he
ordered would be locked for Kevin as long as it remains locked. No one else but
Kevin would be able to modify it, so the name pessimistic implies that there will
be some sort of fight over the resource. Then there's optimistic concurrency
control. This implies that Kevin gets token that allows him to update. Of course,
as long as that token remains fell, it Kevin will be able to perform. The update
optimistic implies that there won't be an issue. But if there is, the token will
tell you that, as you can guess, pessimistic concurrency control isn't possible In
dressed as one of the constraints is statelessness optimistic. Concurrency is
possible. And that token, well, we learned about that already. That's actually a
validator. A strong validator is required for handling issues like these, so we can
use our E tax for it. Let's go back to our example giving gets an altar and the
altar is returned with an e tak value. Friend gets that same altar, and that's
returned with the same attack Value spent updates the altar passing in the dark in
the if match header, the FBI checks his header and compared it with the taxi for
that response. If they match which they currently do, the update can be applied. At
this moment, a new E Tak is generated for the response. The response that includes
that new e tak a swell but then giving sends the update with an East match header
containing the attack. Kevin currently has. It reaches the AP, I and there the AP.
I sees that This does not match with the most current E Tak for that resource. So
the AP I returns of 4 12 Precondition Failed status coat. Kevin's update isn't
applied because he was working on an older version off the course, and that's how
this works. The same applies to Patch, of course. This also drives the case for
separating the cash store from the component that just generates the cash control
and e tak headers. Those e tak head. It's serve different purposes. We don't need a
cash to handle concurrent updates. So even without putting a cash over in front of
the A p I or without using a content delivery network, we can support concurrency
simply by having a component that generates heat acts for us and by sending them
from the client as we just learned about. Let's have a look at how this works with
the demo

Demo - Supporting Concurrency


[Autogenerated] in this demo, we'll have a look at how e tax can help it
concurrency. First thing to do would be to create eat acts for our resources. But
you don't have to do that. The Marvin Not Castell header smell where to generate
heat Axe is already in place as we're starting from the goat we ended up with in
the last team off the previous module with his horse cashing Villa. Where is still
disabled? This is as it should be waiting postman. Let's assume, really, user Kevin
and let's get a course. We still have that request saved so that send it. We get
back course and we get back on E deck. Now let's assume we're the user said will
open a new tap for that. We're going to send get request with the exact same had
her values for the varying headers. In our case, the only had her Kevin passed
through wasn't accepted her. Which value application? Jason. All right, let's send
this. Here's our response, and if you look at the headers, we see any dagga. Swell.
Now we're looking at the back, getting her back their boat exactly the same, and
that makes sense. It is, after all, the same response. So boats finding giving are
not working on the same response. It's still Spencer. He's updating the course
after he's done, he wants to send a put request to update. Of course, you've gotta
put request for that course. Sign up here. And if you look at the body, this will
definitely update the course that send it. We get back a tool for no content. The
update was successful. Now let's go to spend stab again and let's get the scores
again. Try to keep the current e Tagi mind and there we go. We see that the either
has changed and that makes sense. Marvin of Castell Header Stakes the response body
into account when generating any tax. Now let's assume Gavin is done with updating.
He wants to update that same course, so he sends an updated title and description.
Let's send it, and we get back a tool for no ______. That's an issue, as Kevin has
now overwritten, Spence changes. Let's fix this. Let's assume you wantto update a
response, but we want to concurrency check to see if the update can go true. We're
starting from scratch. Giving gets too coarse. We see a familiar eat Jack. Sin gets
the same course. We see the exact same he, doc, let's put it in our clipboard
because we're immediately going to need it. It's still send stern the consumer or
possibly an in between. Cash, if we have that installed, takes this e tak value and
puts it in the if match Heather for our put request. So he had a knife match header
and we give it the dark s value. Let's send this put request it updated the courses
or so far, so good. If so, I don't now get this resort again. We see a different
leader has been generated, but Kevin is still working on his copy. He hasn't got
the most recent copy with the new E tak. So what giving us is sent another put
request. He also adds, And if match other but e tak is using its value is still the
old attack value he got. Let's send the put request. We get back before 12.
Precondition Field. The update isn't allowed. This tells Kevin that he should first
get fresh copy to work on like this. We've implemented optimistic concurrency
checking. That's it for this demo. Let's have a look at the summary

Summary
[Autogenerated] the eat acts we used for validation can also be used as a token or
validator for an optimistic concurrency strategy. This allows concurrent users to
work on the same resorts without running the risk of accidentally overriding a
newer version of the resource. For that, we or rather, the consuming application
sends the E tak if match Heather. If the attack doesn't match with heat like the
server generates for the resource the update will fail with a 4 12 precondition
failed. With that, this course is done. I hope you enjoyed watching it as much as I
enjoyed making it and recording it. But I'm not done yet. Before I go, I have four
more thing to say. You're ready to be awesome.

You might also like