Building a RESTful API with ASP.NET Core 3 Flashcards

1
Q

Is rest a standard? is it protocol agnostic?

A

NO. an arch style… it is protocol agnostico

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the 6 contraintaints (design decisions) that REST has?

A

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).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the payload?

A

Is the data that is sent and/or retrieved along with the request/response.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the Richardson Maturity Model (RMM) and how it relates to REST?

A

It is a set of maturity levels that dictates how much you actually use from the REST standards, or how mature it is.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the level 0 - (swamp of POX - plain old XML) of RMM?

A

You use a single endpoint with a set of statefull calls to achieve a goal; usually using xml

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the level 1 - Resources of RMM?

A

Each resource is mapped to a URI; using post verb only

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the level 2 - Verbs of RMM?

A

Correct HTTP verbs and status codes are used;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the level 3 - Hypermedia of RMM? Which benefit does it bring?

A

The API supports Hypermedia as the engine of the application state (HATEOAS). It brings links to other actions/resources (discoverability).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Which API level can be considered a precondition to a RESTful api?

A

Level 3.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Can the URI api/authors be followed by another noun?

A

NO. should be followed with an ID.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Where to add filters, sorting orders?

A

As a query string.. api/customer?orderby=name

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What a simple controller must have to behave like an endpoint?

A

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]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is a convention-based routing? When is it used the most?

A

endpoints are added to actions on a controller following a convention (explicitly defined). usually used for web applications.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is attribute-based routing?When is it used the most?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How to interact with resources via HTTP methods?

A

https://pasteboard.co/JstVwBx.png

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How to create two http gets to the same source with disambiguation?

A

[HTTPGet(“{authorId:guid}”)]

[HTTPGet(“{authorId:int}”)]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What are the 3 most important 200 status codes which verb uses it?

A

200 - Ok - Get, Success
201 - Ok - Post, Created
204 - Ok - Delete, No content

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What are the 9 most important 400 status codes?

A

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)…

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is the most comon 500 hundred status code?what does it mean?

A

internal error - something bad happened to the server - try again

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is the difference between errors and faults?

A

errors are correctly thrown when something is wrong with the request. and faults means that the API failed to process a correct request.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the benefits of using Ok() instead of new JasonResult()?

A

Ok is more readable and deals with other formats of data other than the jason

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What formatters and content negotiation mean?

A

the client can demand the response in a specific format, and the server can deman the request in a specific format

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How to proper handle unsupported formats in a way that the api returns a 406 error?

A

via services.addcontroller(s => s.ReturnHttpNotAcceptable = true);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

how to add xml as a supported fortmat in asp?

A

s.addcontroller().addxmldatacontractserializerformatters();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What outer facing (DTO) vs entity model means?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Should I always return IActionResult? What’s better for things like swagger?

A

return ActionResult>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What to use to map entity properties to dto object?

A

AutoMapper

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Should i simply install automapper? why not?

A

not… install automapper.extensions.microsoft.dependencyinjection because it plays better with aspnet DI system

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

Where mappings are stored? How to add custom mappings (aka projections)?

A

in the profiles folder, create one for each dto object… inheriting the dto object from map and doing a forMember (if custom)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

How to handle exceptions in the API in a customized way othen than just return a status code 500?

A

by doing an app.UseExceptionHandler(appbuilder => {… appbuilder.run…})

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What is HEAD verb used for? when is it particularly useful?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Can I verb/route the same method twice on aspnet? how?

A

yes… just add extra verbs
[httpget]
[head]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

Where the data from the request can come from?

A

body, form, header, query, route and service

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

Can data from the request be found by inferring types? What is the default source when we work with primitive types?

A

yes. query string (FromQuery)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What is the difference between filtering and searching?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

Are only the fields part of the request filterable?

A

yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

What to do when you need to receive many inputs via query string? What happens to the inferred query string? How to overcome this?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

Will the same DTO always be used for all verbs?

A

No. it’s common to have different dtos for get and post, for example.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

Will the BaseController deal automatically with wrong conversions from the request body to the complex types?

A

Yes. will return 400’s return code

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

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?

A

by returning a CreatedAtRoute(location, bodypayload). by naming the endpoints [httpget(“{asd}”, name = “asd123”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

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?

A

check if the parent resource (defined in the url) exists, otherwise 404

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What to do when you want to post authors along with its courses in one go?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

What to do if aspnet doesn’t handle my binding mechanism (array of guid, for example)?

A

You need to create a custom model binder and assign to the action method in the API.

44
Q

How to support multiple additions of authors in one go?

A

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.

45
Q

is posting to a specific object uri allowed on asp 3? how was that on asp?

A

No… it returns a 405 method not allowed. on asp 2 manual implementation was required

46
Q

What does the option method do? how to implement?

A

return a key value of allow and the comma separated supported verbs. implement manually… response.header =
return ok

47
Q

how to add validation of the input data? can i use the same as i use in my entity?

A

works out of the box as long as the dto has the data annotations.

48
Q

How to implement my own custom validations?

A

by implementing the IValidatableObject by the DTO (once this is the final input) and implementing the method. usually the classname is returned along

49
Q

Will my custom validator be called when data annotation validation fails? Does that apply to custom data annotation attributes?

A

No. Yes.

50
Q

Instead of using IValidatableObject, how to implement my own data annotanion attribute?

A

By creating a new class with the name of the validation and extending from ValidationAttribute.

51
Q

Is the API response from aspnet 3 fully compliant with the RFC? What to do then?

A

No. You can return the proper return code 422 by implementing you own InvalidModelStateResponseFactory which is accessible in the services class.

52
Q

What is the problem behind data annotation validations and IValidatableObjects? What is the other approach to overcome this?

A

they are hard to test and bound to the entities. using FluentValidation library.

53
Q

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?

A

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

54
Q

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?

A

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.

55
Q

What code to return after a success put operation? should it have content? could it be the same return we do with a post?

A

204 - no content. yes… seems to be better to also return helper field like lastmodified and stuff with this.

56
Q

How to minimize code duplication for update and create dtos? Does data anotation also work in this case?

A

create a base class with virtual properties that can be overriden. Yes, works and can be overriden.

57
Q

Why executing a put request in a collection of items can be destructive? (e.g courses) What to do then?

A

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.

58
Q

What is upserting?

A

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.

59
Q

What is a JSON patch document?

A

is a list of operations that will be applied to an existing resource in order to change its content.

60
Q

jsonpatchdocument is part of default aspnet core projects?

A

no… need to be added via nuget.

61
Q

is it necessary to use newtonsoft.json package to overcome default json package limitations?

A

yes… then needed to be applied to the services.

62
Q

The order of the serializers impact the default serialization process?

A

yes… json first and then XML

63
Q

Are json patch documents validated automatically?

A

NO. need to add manual validations:
patchdoc.applyTo(courseToPatch, modelstate);
if !tryvalidatemodel(courseToPatch, ModelState) return ValidationProblem(ModelState)

64
Q

How to make a controller to use our custom model validator?

A

needs to override ValidationProblem(

)

65
Q

does upserting with patch need custom logics? what about the validations?

A

yes for both.

66
Q

what does a delete request returns?

A

204 nocontent

67
Q

What is cascade delete on entity framework core, is it the default behavior?

A

delete will cascade to all child objects. enabled by default.

68
Q

is deleting collections recommended?

A

NO.

69
Q

What are the advanced conecepts that were not covered here that makes our api NOT fully restful?

A

HATEOAS, advanced content negotiation, caching and concurrency, paging, sorting and data shapping.

70
Q

What benefit the IQueryable brings? Why?

A

Enables LINQ. Because it allows creating an expression tree via LINQ.

71
Q

How to allow pagination? Where is it defined?

A

by doing a skip and take in the linq query. defined as query string

72
Q

should the pagination metadata returned in the response body? where then?

A

NO. as header information.

73
Q

What is a good way of implementing a paged list on aspnet core? what is the gotcha? Should we do paging by default?

A

by extending a list and implementin the properties accordingly. The gotcha is around receiving a IQueriable so that improving performance? Yes, paging by default.

74
Q

What are the properties that define a pagination endpoint? Where these properties are assigned?

A

totalCount, pageSize, currentPage, totalPages, previousPageLink and nextPageLink. In the X-Pagination header

75
Q

what is used to implement a good generic order by clause in the api?

A

system.linq.dynamic.core

76
Q

What is the lifetime of a lightweight stateless dependency recommended by .net core team?

A

transient

77
Q

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?

A

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)

78
Q

What is data shapping and why is it useful?

A

data shapping is the act of allowing the consumer to decide which fields will be returned. useful to reduce network traffic.

79
Q

How to implement data shapping, how to avoid overheads?

A

by using expandObject… we can avoid overheads by doing the reflection once and the populate the newly dynamic class.

80
Q

what is HATEOAS in simple terms?

A

means that the resource will have links to other resources

81
Q

what happens when HATEOAS is not implemented?

A

the client needs to know too much and it is hard to evolve the API.

82
Q

What does HATEOAS means about client controls?

A

they are learned on the fly (links will vary based on the current API state and version).

83
Q

Are there new rest api standards being developed? which one is backed by MS?

A

yes… there are several under development… microsoft backs up odata.org

84
Q

What is advanced content negotiation and what custom media type vendor means? Where is this custom media type defined?

A

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

85
Q

What is a semantic media type?

A

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)

86
Q

how to avoid api versioning?

A

via code on demand principle… but this is difficult, versioning is pragmatically acceptable.

87
Q

what are the three types of cache?

A

client cache, gateway cache and proxy cache

88
Q

What is the gateway cache? how is it also know?

A

The gateway cache lives in the server and is aka reverse proxy cache and http accelerators

89
Q

Whats ithe proxy cache?

A

usually used in big networks such as ISP providers.

90
Q

What is the response cache attribute? what is the default unit of measure used for the cache?

A

Is a header property “cache-control: max-age:120”. measured in seconds.

91
Q

How to enable http cache in our rest api?

A

by adding a cache middleware and by adding a [ResponseCache (duration = 120)] attribute to the endpoint’s methods

92
Q

Where the app.UseResponseCaching needs to be added?

A

before useRouting and useEndpoints, otherwise our cache will never be hit.

93
Q

What is a cache profile? Where is it applied?

A

Allow setting caching rules to dfferent endpoints. Applied to the controller level [ResponseCache (CacheProfileName = “myProfileKey”)]

94
Q

How does the expiration model cache works?

A

it has a property containing a datetime defining the “due” date of the data.

95
Q

What is the difference between private and public caching?

A

private means each application has its own cached data and controls. public means the cache is shared to everyone.

96
Q

What is the difference between private and public caching from the network and api hits perspective?

A

private uses less bandwidht (not stored in the server) and public doesn’t save bandiwith however drastically reduces requests directly to the api.

97
Q

How does the validation model cache works? What is strong and weak validators?

A

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

98
Q

What is the holy grail of caching?

A

Is when the expiration and validation chaching models are used for both private and public caches.

99
Q

What are the cache-control directives?

A

https://pasteboard.co/JvmgD98.png”

100
Q

How to implement the validation cache to our aspnet projects? is there a lib available for that? Where place that in the middleware?

A

Can be implemented via the use of marvin.cache.headers package. put before routing and before endpoints.

101
Q

How to keep all instances of my api in sync with the cache data?

A

you can use redis.

102
Q

Will CDNs (akamai, cloudflare etc) comply with our cache tags? What about common proxies?

A

Yes… that should suffice for the backend engineer. Yes for common proxies such as squid.

103
Q

Is cache invalidation implemented by expiration and validation approaches? What to do for complex scenarios (such as indirect resource changes)?

A

yes. manual cache invalidation needs to be written or use cdn-provided SDKs.

104
Q

What are the two concurrency strategies?

A

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

105
Q

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?

A

412 - precondition failed. Needs to have a if-Match: