Building a RESTful API with ASP.NET Core 3 Flashcards
Is rest a standard? is it protocol agnostic?
NO. an arch style… it is protocol agnostico
What are the 6 contraintaints (design decisions) that REST has?
1 - Uniform Interfaces: API and consumers share one single technical interface: API;
2 - Client-Server: They are completelly separated;
3 - Statelessness: state is contained within the request;
4 - Layered system: layers can be added or removed in a transparent way to other layers;
5 - Cacheable: each RESPONSE message must explicitly state if it can be cached or not (ETag, lat-modified and etc)
6 - Code on demand (optional): server can extend client functionality (usually applicable for webapps).
What is the payload?
Is the data that is sent and/or retrieved along with the request/response.
What is the Richardson Maturity Model (RMM) and how it relates to REST?
It is a set of maturity levels that dictates how much you actually use from the REST standards, or how mature it is.
What is the level 0 - (swamp of POX - plain old XML) of RMM?
You use a single endpoint with a set of statefull calls to achieve a goal; usually using xml
What is the level 1 - Resources of RMM?
Each resource is mapped to a URI; using post verb only
What is the level 2 - Verbs of RMM?
Correct HTTP verbs and status codes are used;
What is the level 3 - Hypermedia of RMM? Which benefit does it bring?
The API supports Hypermedia as the engine of the application state (HATEOAS). It brings links to other actions/resources (discoverability).
Which API level can be considered a precondition to a RESTful api?
Level 3.
Can the URI api/authors be followed by another noun?
NO. should be followed with an ID.
Where to add filters, sorting orders?
As a query string.. api/customer?orderby=name
What a simple controller must have to behave like an endpoint?
data anotaded as [APIController], extending ControllerBase, defining the Route[(“api/authors”)] data anotation to the controller and defining the data anotation verb to the action [HTTPGet]
What is a convention-based routing? When is it used the most?
endpoints are added to actions on a controller following a convention (explicitly defined). usually used for web applications.
What is attribute-based routing?When is it used the most?
The routing is defined via the combinations of the controller name and data anotations in the action methods inside the controllers. used the most for APIs
How to interact with resources via HTTP methods?
https://pasteboard.co/JstVwBx.png
How to create two http gets to the same source with disambiguation?
[HTTPGet(“{authorId:guid}”)]
[HTTPGet(“{authorId:int}”)]
What are the 3 most important 200 status codes which verb uses it?
200 - Ok - Get, Success
201 - Ok - Post, Created
204 - Ok - Delete, No content
What are the 9 most important 400 status codes?
400 - Bad request - Generic
401 - Unauthorized (authentication issues)
403 - Forbidden (authorization issues)
404 - not found
405 - method not allow (e.g send a post to the authors endpoint)
406 - not acceptable (the payload response format asked is not supported)
409 - Conflict (used to handle concurrency issues: the data has been changed by someone else)
415 - same as 406, but the issue is with the REQUEST payload
422 - unprocessable entity - semantic mistakes (validation)…
What is the most comon 500 hundred status code?what does it mean?
internal error - something bad happened to the server - try again
What is the difference between errors and faults?
errors are correctly thrown when something is wrong with the request. and faults means that the API failed to process a correct request.
What is the benefits of using Ok() instead of new JasonResult()?
Ok is more readable and deals with other formats of data other than the jason
What formatters and content negotiation mean?
the client can demand the response in a specific format, and the server can deman the request in a specific format
How to proper handle unsupported formats in a way that the api returns a 406 error?
via services.addcontroller(s => s.ReturnHttpNotAcceptable = true);
how to add xml as a supported fortmat in asp?
s.addcontroller().addxmldatacontractserializerformatters();
What outer facing (DTO) vs entity model means?
means that our internal entity model should NOT be directly exposed to the external world. instead we should use outer facing models and translate into them via automapper
Should I always return IActionResult? What’s better for things like swagger?
return ActionResult>
What to use to map entity properties to dto object?
AutoMapper
Should i simply install automapper? why not?
not… install automapper.extensions.microsoft.dependencyinjection because it plays better with aspnet DI system
Where mappings are stored? How to add custom mappings (aka projections)?
in the profiles folder, create one for each dto object… inheriting the dto object from map and doing a forMember (if custom)
How to handle exceptions in the API in a customized way othen than just return a status code 500?
by doing an app.UseExceptionHandler(appbuilder => {… appbuilder.run…})
What is HEAD verb used for? when is it particularly useful?
HEAD is used to check if a resource exists, equal to get but without body. Very useful when ETags and other similar multi-use validations are used
Can I verb/route the same method twice on aspnet? how?
yes… just add extra verbs
[httpget]
[head]
Where the data from the request can come from?
body, form, header, query, route and service
Can data from the request be found by inferring types? What is the default source when we work with primitive types?
yes. query string (FromQuery)
What is the difference between filtering and searching?
Filtering means the consumer define what are the filters to apply via query string. Search is simply a term that the api defines on how to search it.
Are only the fields part of the request filterable?
yes
What to do when you need to receive many inputs via query string? What happens to the inferred query string? How to overcome this?
It’s best to create a complex type (class) to handle this. The inferred query string will no longer work. Solved by add a [FromQuery] data annotation.
Will the same DTO always be used for all verbs?
No. it’s common to have different dtos for get and post, for example.
Will the BaseController deal automatically with wrong conversions from the request body to the complex types?
Yes. will return 400’s return code
During a post, how to express the location where the resource is created? Where the location appears? How to refer to existing endpoints without concatenating manually URIs?
by returning a CreatedAtRoute(location, bodypayload). by naming the endpoints [httpget(“{asd}”, name = “asd123”)
What is the first check that needs to be done in the API when a consumer wants to add a resource that is child of another one?
check if the parent resource (defined in the url) exists, otherwise 404
What to do when you want to post authors along with its courses in one go?
The authorDTO must contain in its definition an ICollection of courseDTO (initialized) and the repository needs to also be also to handle that (needs to be able to create guid for the author and for the courses when added… entity framework takes care of the rest.
What to do if aspnet doesn’t handle my binding mechanism (array of guid, for example)?
You need to create a custom model binder and assign to the action method in the API.
How to support multiple additions of authors in one go?
it is suggested to create a new endppoint that support posts and read of collection, but I found it pretty shitty. i’d used the same endpoint.
is posting to a specific object uri allowed on asp 3? how was that on asp?
No… it returns a 405 method not allowed. on asp 2 manual implementation was required
What does the option method do? how to implement?
return a key value of allow and the comma separated supported verbs. implement manually… response.header =
return ok
how to add validation of the input data? can i use the same as i use in my entity?
works out of the box as long as the dto has the data annotations.
How to implement my own custom validations?
by implementing the IValidatableObject by the DTO (once this is the final input) and implementing the method. usually the classname is returned along
Will my custom validator be called when data annotation validation fails? Does that apply to custom data annotation attributes?
No. Yes.
Instead of using IValidatableObject, how to implement my own data annotanion attribute?
By creating a new class with the name of the validation and extending from ValidationAttribute.
Is the API response from aspnet 3 fully compliant with the RFC? What to do then?
No. You can return the proper return code 422 by implementing you own InvalidModelStateResponseFactory which is accessible in the services class.
What is the problem behind data annotation validations and IValidatableObjects? What is the other approach to overcome this?
they are hard to test and bound to the entities. using FluentValidation library.
When executing a full update (PUT) what happens to the missing fields available in the entity itself (e.g: id)? What about the missing fields that are in the dto?
They are all kept once these fields are NOT available in the dto. the missing fields available in the DTO will get their default value, which is null
Do the update method in the repo need to do anything? what is necessary to do then? Why keep this method and call it afterall?
no… because the mapper already changed the entity. just call save… because different technologies might need to use the update method… remember: we’re coding agains a repository interface which is technology agnostic.
What code to return after a success put operation? should it have content? could it be the same return we do with a post?
204 - no content. yes… seems to be better to also return helper field like lastmodified and stuff with this.
How to minimize code duplication for update and create dtos? Does data anotation also work in this case?
create a base class with virtual properties that can be overriden. Yes, works and can be overriden.
Why executing a put request in a collection of items can be destructive? (e.g courses) What to do then?
because the “by the book” put replaces the existing content with the request body… that means the existing items should be deleted and re-inserted. might be a good idea not implementing this funcionality.
What is upserting?
Is when the consumer is also able to create guids and therefore won’t post (otherwise guid will get replaced). Therefore, this consumer will call the put method, which will insert the value in the database.
What is a JSON patch document?
is a list of operations that will be applied to an existing resource in order to change its content.
jsonpatchdocument is part of default aspnet core projects?
no… need to be added via nuget.
is it necessary to use newtonsoft.json package to overcome default json package limitations?
yes… then needed to be applied to the services.
The order of the serializers impact the default serialization process?
yes… json first and then XML
Are json patch documents validated automatically?
NO. need to add manual validations:
patchdoc.applyTo(courseToPatch, modelstate);
if !tryvalidatemodel(courseToPatch, ModelState) return ValidationProblem(ModelState)
How to make a controller to use our custom model validator?
needs to override ValidationProblem(
)
does upserting with patch need custom logics? what about the validations?
yes for both.
what does a delete request returns?
204 nocontent
What is cascade delete on entity framework core, is it the default behavior?
delete will cascade to all child objects. enabled by default.
is deleting collections recommended?
NO.
What are the advanced conecepts that were not covered here that makes our api NOT fully restful?
HATEOAS, advanced content negotiation, caching and concurrency, paging, sorting and data shapping.
What benefit the IQueryable brings? Why?
Enables LINQ. Because it allows creating an expression tree via LINQ.
How to allow pagination? Where is it defined?
by doing a skip and take in the linq query. defined as query string
should the pagination metadata returned in the response body? where then?
NO. as header information.
What is a good way of implementing a paged list on aspnet core? what is the gotcha? Should we do paging by default?
by extending a list and implementin the properties accordingly. The gotcha is around receiving a IQueriable so that improving performance? Yes, paging by default.
What are the properties that define a pagination endpoint? Where these properties are assigned?
totalCount, pageSize, currentPage, totalPages, previousPageLink and nextPageLink. In the X-Pagination header
what is used to implement a good generic order by clause in the api?
system.linq.dynamic.core
What is the lifetime of a lightweight stateless dependency recommended by .net core team?
transient
How to implement the sort without switches (taking into consideration we’re using DTOs)? Will sometimes the order be inverter or one to many mappings?
by creating a map between the entity and the dto. yes, sometimes it’s necessary to invert (age vs dob, name vs first and last name)
What is data shapping and why is it useful?
data shapping is the act of allowing the consumer to decide which fields will be returned. useful to reduce network traffic.
How to implement data shapping, how to avoid overheads?
by using expandObject… we can avoid overheads by doing the reflection once and the populate the newly dynamic class.
what is HATEOAS in simple terms?
means that the resource will have links to other resources
what happens when HATEOAS is not implemented?
the client needs to know too much and it is hard to evolve the API.
What does HATEOAS means about client controls?
they are learned on the fly (links will vary based on the current API state and version).
Are there new rest api standards being developed? which one is backed by MS?
yes… there are several under development… microsoft backs up odata.org
What is advanced content negotiation and what custom media type vendor means? Where is this custom media type defined?
Means that the client might request the response in json including links (HATEOAS). custom media type vendors define their own contract definition. in the header, field Accept
What is a semantic media type?
is a media type that defines how the “shape” of the data that is being retrived… might be a simple one and a full (more verbose)
how to avoid api versioning?
via code on demand principle… but this is difficult, versioning is pragmatically acceptable.
what are the three types of cache?
client cache, gateway cache and proxy cache
What is the gateway cache? how is it also know?
The gateway cache lives in the server and is aka reverse proxy cache and http accelerators
Whats ithe proxy cache?
usually used in big networks such as ISP providers.
What is the response cache attribute? what is the default unit of measure used for the cache?
Is a header property “cache-control: max-age:120”. measured in seconds.
How to enable http cache in our rest api?
by adding a cache middleware and by adding a [ResponseCache (duration = 120)] attribute to the endpoint’s methods
Where the app.UseResponseCaching needs to be added?
before useRouting and useEndpoints, otherwise our cache will never be hit.
What is a cache profile? Where is it applied?
Allow setting caching rules to dfferent endpoints. Applied to the controller level [ResponseCache (CacheProfileName = “myProfileKey”)]
How does the expiration model cache works?
it has a property containing a datetime defining the “due” date of the data.
What is the difference between private and public caching?
private means each application has its own cached data and controls. public means the cache is shared to everyone.
What is the difference between private and public caching from the network and api hits perspective?
private uses less bandwidht (not stored in the server) and public doesn’t save bandiwith however drastically reduces requests directly to the api.
How does the validation model cache works? What is strong and weak validators?
Based on etags and/or last-modified dates. Strong changes etag if anything within the body or header is changed. Weak depends on how much is changed (server decides - equivalence not equity).
more at: https://pasteboard.co/JvmcGIv.png
What is the holy grail of caching?
Is when the expiration and validation chaching models are used for both private and public caches.
What are the cache-control directives?
https://pasteboard.co/JvmgD98.png”
How to implement the validation cache to our aspnet projects? is there a lib available for that? Where place that in the middleware?
Can be implemented via the use of marvin.cache.headers package. put before routing and before endpoints.
How to keep all instances of my api in sync with the cache data?
you can use redis.
Will CDNs (akamai, cloudflare etc) comply with our cache tags? What about common proxies?
Yes… that should suffice for the backend engineer. Yes for common proxies such as squid.
Is cache invalidation implemented by expiration and validation approaches? What to do for complex scenarios (such as indirect resource changes)?
yes. manual cache invalidation needs to be written or use cdn-provided SDKs.
What are the two concurrency strategies?
pessimistic (resource is locked, not possible for APIs) and optimistic (resource can be update as long as the token is valid - such as etag).
details at: https://pasteboard.co/JvmtZns.png
What is the status code that is returned when the etags does not match? What is the property that needs tp be defined in the header to trigger this?
412 - precondition failed. Needs to have a if-Match: