Populating new form data from REST api - rest

I've come from a background of ASP.Net MVC where when the user wants to create a new entity the server returns values to populate drop down lists(for example).
Now I'm doing a UI that is invoking a REST Api. I have my urls for creating/retrieving etc but this is purely for actual resources. How would the REST be defined to get data to populate the create form.
For example:
a user wants to create a new order. They go to the 'create order' screen and need to select their payment method. They have 3 payment methods (card, paypal, amazon) but the logic on the server side knows that amazon cannot be accepted on this order. How would I go about letting the UI know what can be populated in the drop down list using REST?
I can't seem to get this to fit into REST principles but then I don't want the user to submit amazon and then the server return a Bad Request, just seems bad implementation.
Thanks

Related

Handling User Preferences/States in REST API

We're starting to migrate our Website to a REST Service based system and are in the process of developing the core right now.
In our current setup a user has one or more "accounts" assigned which define what data he can see on the website. Only one account can be active for a given user at any time. Right now we store the selected account in the database and use it to filter all queries.
Now I'm not sure how to handle this properly in a REST environment. Possible solutions I found are:
Sending the requested account with every request
Storing the current account in the auth token. (We're using JWT for that)
Having the current account stored on the server and calling a specific resource to change it
Each of these has its pros and cons for our setup. Currently we're using the 3rd approach in our Website. But what would be the correct way to handle such a thing in a REST environment?
Yea the design you are dealing with is fairly bad, and what you really want to do is remove the state completely out of this system.
For that reason the first option is by far superior:
Sending the requested account with every request
If this is simply an id, there's a very simple way to do this, just prefix all your (relevant) routes / uris with this account id. For example:
http://api.example.org/accounts/{id}/...
This way the 'state' is maintained by virtue of which url you are accessing, and the server can be unaware of the state.

DDD Responsibilities of Controller on MVC application

I'm refactoring a application to DDD, and so far so good but i got a doubt about some responsibility and what are the best approaches to solve it.
The application is a web app that call center agents use, with CRM features, the backend is a REST API.
The use case is as follows: The agent calls to a customer and need to collect some information / offer promotions etc.
After calling the customer and talked to him, he needs to fill some information for this contact attempt, some of that information is combo box with data filled from the database, and it sends a POST with the IDs of the entities to a endpoint to register it.
So we have a endpoint contactAttempt that receive the data, customerId, agentId, some combo box info (subjectId, reasonId, extraInfo1, extraInfo2), the extra info doesn't call that, but just to simplify.
That information is deserialized to a DTO object that is passed to a application service, which consult the respective repository to check if the ids are valid and return the Entities, if the entities are not found, it throws a exception that the controller catches and answer the client with a message.
If all the entities are valid, there are some domain rules, like if is the first contact with the customer, sends a welcome e-mail, and other stuff.
My doubt is with this steps of fetching entities from the Repository, it should be like that or should i fetch it in the controller, and if all that i need is present, then i pass to the domain service with just the logic needed to apply the business rules?
What are the pros and cons of the mentioned approaches?
Is there other approaches?
In the context of a MVC, what is the responsibility of the Controller?
The MVC is responsible to deserialize the HTTP request in a message for the "application layer".
So it should get from the querystring/body/headers all the values needed and pass to a service as immutable values (command). This because the application service (handler, whatever) should execute the command transactionally, and if the entities (so, the behavior) are accessed outside the application layer, you can't assure that no modification happens outside the application layer.

REST API Design: When should we use association in Uri for the resources?

We have simple e-commerce website where we have several products. Currently, each product has "Place order" button.
When user clicks on this button, we show user a form to fill Name, Mobile number and address. We don't support any monetary transaction. Once user fills this form, the order is saved to database. The order table has OrderId, ProductId, UserName, UserMobile.
We are designing API to save the user order. Should we have association b/w product and order while designing this?
For example URI to save the user order should be like:
POST /api/products/1/lead/ - The request body has user information i.e. name,mobile,address. OR
POST /api/lead/ - The request body has "PRODUCT ID" and user information i.e. name,mobile,address.
I am confused whether productId should be in request URI or in the request body? How do we make such decision?
Given that
you're first navigating to a product, before actually placing the order
the product id has nothing in common with the UserInformation model that you're posting
I'd go with the first option: POST /api/products/1/lead/
I would always go with a more shallow route for representing resources, just for the sake of simplicity. No, a nested route isn't complicated or anything, but I've seen nesting go really far. So I would keep it as shallow as possible unless...
1) You plan on having more than one thing that can have a lead. For example, you can have a lead on a product:
api/products/1/lead
or a lead on a managed service that you all provide or something (I'm reaching right now):
api/managed_services/2/lead
You could pass that info in the body always, but I imagine it would become a little cumbersome to base what resource to create based on what properties were defined in the json.
2) You plan on breaking out that route and having it go to a different service eventually. Maybe this app will have to scale substantially and a ton of users will be hitting this route moreso than any other endpoint in the system. It's a lot easier to redirect all requests to a different microservice based on the url starting with api/products than it would be redirect based on the request body.
But honestly, I don't think it matters too much. As long as it's easy for your clients to consume.

How should I design a RESTful URL to validate an object

Without moving away from the RESTful paradigm, how could you model object validation in a RESTful way? Best to explain the theoretical use case I've come up with...
Imagine you have a system with a very thin web layer making calls to back-end RESTful services. Say a user visited a registration form and submitted it, the web layer would send the unvalidated data straight to a back-end service and, if the service responds with validation errors in JSON format, these can be sent back to the user as HTML.
However, imagine we want to have AJAX behaviour on the form. For example, the user enters their email address and we want to validate using AJAX, sending an error to the user if their email address is already registered.
Would it make sense to implement a single call to validate just the email address, or could the whole object be sent and validated in a back-end service? If the latter, what URL could you use to only validate an object, rather than actually create it?
In the past I have used the notion of a sandbox sub-resource to do what you are suggesting,
http://example.com/customer/23/sandbox
This allows me to POST deltas and have the changes applied and validated but not actually committed. This works quite well for the traditional "save/cancel" type dialogs.
However, I found dealing with those deltas to be a real pain, so I developed a different media type that recorded a sequence of events on the client and then posted that document to the sandbox resource. By replaying the sequence of events I could update and validate the server side resource in a simpler fashion.
Later on I realized that I really didn't need the distinct "sandbox" resource and now I just post the "sequence of events" document directly to the resource it is affecting. I have some data in the document itself that determines whether the changes are going to be permanent or just transient. It just depends if the user has pressed the save button yet or not.
Validating a single form field can improve user experience while the user is filling the form, but when the form is submitted, I would validate the whole object, because it's less error prone. The URL can be simply https://mysite.com/users/emailvalidator for validating the e-mail only (a single field), and the form could be POSTed to https://mysite.com/users (the whole object). In the former case, the URL tells clearly that the resource you want to use is an object which is able to validate an e-mail.

ASP.net MVC removing repeated data calls

Ive got a asp.net mvc site that works with ASP.net Authentication. I have a UserInformation table which stores extra information on each user aswell. On pretty much every page i am calling to the database to pull the UserInformation record for the current user at least once.
Im thinking all these repeated data calls for the same information has to be overkill. Is there anyway i can cut these down? Caching? Storing the userinformation record for future use etc etc?
Im sure im not the first person to come across this issue, so i didnt want to reinvent the wheel.
Thanks in advance
You could use a custom IIdentity and IPrincipal. Here's a nice article describing how to achieve this (the interesting part is happening in the btnAuthenticate_Click method which in an ASP.NE MVC application would be the authenticate controller action, here is emitted the authentication ticket with custom data). In this example the idea is that the authentication ticket is manually created and the userData property is used to store additional information. This might not be appropriate for your case if you have lots of data because this is stored in a cookie. But instead of using the userData you could store it somewhere else like Session or Cache. You could also write a custom [Authorize] attribute to deal with the custom principal (the part that corresponds to the Application_AuthenticateRequest method in the article should go in this custom authorization filter in order to reconstruct the user back).