Laravel Service layer: passing HTTP request from controller to service - laravel

I am developing a Laravel application and using a Service layer pattern to isolate business logic. What I come across in all tutors/articles is passing the HTTP request object from the controller directly into the service. To me, it goes against the principle of a service being an API-independent piece of code that has a single responsibility for a certain functionality. Imagine I would like to call the service from the command line or from an event handler, I would then have to construct an HTTP Request object to pass to the controller.
Same goes for validation: as far as I understand, the validator would on failure either redirect the user back (which may have no sense in the case of command line or event handler) or return an HTTP error.
On the other hand, with a lot of form fields, there should be some structure to pass the data in, and the form itself already gives such structure.
What are best practices regarding this?

Related

What is the difference between method handlers such .get, .post and actions such as .list, .create

I am learning Django Rest Framework and one of the things I have noticed is that Viewsets provide actions such as .list, .post instead of method handlers such as .get, .post which in turn are provided by Views. The documentation says that actions are more flexible than method handlers but I can't seem to find any reason for this. Could you please share some information on why does Viewsets use actions and not the method handlers?​
request handlers like .get() and .post() are based on http request methods, while actions like .create() or .list() are from a functionality point of view. Suppose you have a view class that can return a single user's info by user id or return all users in sorted order. These two requests are all GET requests from the client side, but with different parameters and purposes. If you just want to use .get() handler in this case you will need to define two view functions and register the two urls in url config. Or you can use ViewSet class or generic view with mixins that has action functions .list() and .retrieve() to handle these requests, then using router class to set the url configs that follows the REST url standards.
GET and POST are the only HTTP methods to use when dealing with forms.
Django’s login form is returned using the POST method, in which the browser bundles up the form data, encodes it for transmission, sends it to the server, and then receives back its response.
GET, by contrast, bundles the submitted data into a string, and uses this to compose a URL. The URL contains the address where the data must be sent, as well as the data keys and values. You can see this in action if you do a search in the Django documentation, which will produce a URL of the form https://docs.djangoproject.com/search/?q=forms&release=1.
GET and POST are typically used for different purposes.
Any request that could be used to change the state of the system - for example, a request that makes changes in the database - should use POST. GET should be used only for requests that do not affect the state of the system.
GET would also be unsuitable for a password form, because the password would appear in the URL, and thus, also in browser history and server logs, all in plain text. Neither would it be suitable for large quantities of data, or for binary data, such as an image. A Web application that uses GET requests for admin forms is a security risk: it can be easy for an attacker to mimic a form’s request to gain access to sensitive parts of the system. POST, coupled with other protections like Django’s CSRF protection offers more control over access.
On the other hand, GET is suitable for things like a web search form, because the URLs that represent a GET request can easily be bookmarked, shared, or resubmitted.

Spring MVC REST API: Invoke controller method programmatically given URL and JSON request body

I have a general REST API (developed using Spring MVC) that takes a list of API requests as its request body.
Each API request in the list has its own URL and request body.
In the implementation of this general REST API, I need to call the corresponding Spring controller method (in the same app) for each of these individual API requests (with their appropriate URL and request body).
(I will then merge all those individual API responses and return it in one big response from the general REST API).
I've been searching around, but I'm unclear how to programmatically call Spring to execute each individual API request. I would ideally like to get back the ResponseEntity from each call instead of the actual JSON response.
(More information:
On the same app server as the general API, I need to translate the URL and JSON request body for each individual API into the arguments to the controller method. I also need to take the URL and have Spring determine which controller method to invoke itself.)
Any help would be greatly appreciated.
Thanks,
Matt
Answer depend on whether the individual URLs that you are planning to invoke is with in the same server (Accessible without using network call) or not
If it is with in the same app server, spawn multiple threads and invoke the individual methods and join the response together and send it back
If it is not within the same app server, there are many Async Restclients are there besides spring's own webclient/restTemplate etc

Extending WebApi response using OWIN Middleware

I have a WebApi project based on OWIN, and I wanted to extend the result of WebApi call with some additional data, for example add localization data to response.
Initial idea was to inject that logic in a pipeline and once we get a result of API call I just have wrap that json with wrapper that will contain translation and some additional properties like time of execution.
So I wrote my own middleware put it after UseWebApi() but it's not executed because WebApi doesn't call "Next" in case it handles the request
So the question is:
How can I modify/extend Json returned by WebApi middleware?
Any other ideas how to handle such a problem with an action that has to be executed for all requests?
Thanks
Regarding the middleware:
you need to place your middleware before UseWebApi, and put your logic after invoking the next middleware; in this case your code well execute after Web API is done processing the request.
You might also want to check the following blog post, it discusses the same scenario of yours:
http://www.devtrends.co.uk/blog/wrapping-asp.net-web-api-responses-for-consistency-and-to-provide-additional-information

web api 2 singleton

I have an in-memory object graph accessible via ASP.NET WEB API 2. GET, POST, PUT, DELET code executes correctly except that the accessed collection is "untouched" when the next action methon is called. I use Fiddler to test and my own clients. Looks like the collection is reconstructed for every call.
I however need a single object graph that is accessed by all clients. Can Web API be configured to use singleton data, like WCF? Or do I have to make the data a singleton myself? I am testing in VS.2013, I don't have a dedicated OWIN host yet.
Create a message handler class that derives from DelegatingHandler.
Pass your graph into the constructor.
Add an instance of your handler to the config.MessageHandlers collection.
When a request passes through your message handler, add your graph to the properties collection of the request.
Create an extension method to make it easy to pull the graph out of the request object.
Make sure your graph is thread safe.

Is server-side validation an appropriate use of ASP.NET WebAPI ApiController action

Before WebAPI, I did all client-side remote validation calls using regular MVC action methods. With WebAPI, I can now have POST, PUT, DELETE, and GET methods on an ApiController. However, validation still needs to happen.
I have successfully been able to put remote validation action methods on an ApiController and get them to work. Before submitting a POST, PUT, or DELETE for a resource, the client can POST to one or more validation URL's to validate user input and receive appropriate validation messages.
My question is, should these remote validation actions be on an ApiController? Or a regular MVC controller? It seems to me having them all in the ApiController makes the most sense, because that class can then encapsulate everything having to do with resource (and resource collection) mutations.
Update: reply #tugberk
I should elaborate. First, we are not using DataAnnotations validation. There are already rich validation rules and messages configured on the domain layer commands using FluentValidation.NET. Many of the validation classes use dependency injection to call into the database (to validate uniqueness for example). FluentValidation has good pluggability with MVC ModelState, but I have not found a good way to plug it into WebAPI ModelState yet.
Second, we are doing validation at the POST, PUT, and DELETE endpoints. Clients do not need to know the validation endpoints in order to discover what went wrong. Here is an example:
var command = Mapper.Map<CreateCarCommand>(carApiModel);
try
{
_createHandler.Handle(command);
}
catch (ValidationException ex)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
}
Clients will get a 400 response along with a message indicating what went wrong. Granted, this is not as granular as the response in the example you linked to. Because we are just returning a string, there is no easy way to parse out which fields each validation message belongs to, which is needed for our own HTML + javascript client of the API. This is why I spiked out adding more granular validation endpoints (as a side note, they are consumed by field-specific knockout-validation calls on our javascript client).
I am assuming that you are referring to something similar to ASP.NET MVC Remote Validation by saying remote validation. In that case, I don't think that your HTTP API needs a remote validation. Think about a scenario where I need to consume your HTTP API with my .NET application and assume that you have a remote validation. Two things bother me here:
That remote validation is not discoverable unless you are providing a .NET client for your API by yourself and put that logic inside that client.
Assuming that the remote validation is there for the .NET client and the application will make a validation call to the server before sending the actual request, this is just a overkill.
In my opinion, the user send a request to your API and you should make the validation there. You can find a sample from the following URL:
ASP.NET Web API and Handling ModelState Validation

Resources