Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS and Web Service Interaction Best Practices

I have a small website I implemented with AngularJS, C# and Entity Framework. The whole website is a Single Page Application and gets all of its data from one single C# web service.

enter image description here

My question deals with the interface that the C# web service should expose. For once, the service can provide the Entities in a RESTful way, providing them directly or as DTOs. The other approach would be that the web service returns an object for exactly one use case so that the AngularJS Controller only needs to invoke the web service once and can work with the responded model directly.

To clarify, please consider the following two snippets:

  // The service returns DTOs, but has to be invoked multiple 
  // times from the AngularJS controller
  public Order GetOrder(int orderId);
  public List<Ticket> GetTickets(int orderId);

And

  // The service returns the model directly
  public OrderOverview GetOrderAndTickets(int orderId);

While the first example exposes a RESTful interface and works with the resource metaphor, it has the huge drawback of only returning parts of the data. The second example returns an object tailored to the needs of the MVC controller, but can most likely only be used in one MVC controller. Also, a lot of mapping needs to be done for common fields in the second scenario.

I found that I did both things from time to time in my webservice and want to get some feedback about it. I do not care too much for performance, altough multiple requests are of course problematic and once they slow down the application too much, they need refactoring. What is the best way to design the web service interface?

like image 275
WeSt Avatar asked Nov 11 '22 03:11

WeSt


1 Answers

I would advise going with the REST approach, general purpose API design, rather than the single purpose remote procedure call (RPC) approach. While the RPC is going to be very quick at the beginning of your project, the number of end points usually become a liability when maintaining code. Now, if you are only ever going to have less than 20 types of server calls, I would say you can stick with this approach without getting bitten to badly. But if your project is going to live longer than a year, you'll probably end up with far more end points than 20.

With a rest based service, you can always add an optional parameter to describe child records said resource contains, and return them for the particular call.

like image 132
Nathan Tregillus Avatar answered Nov 14 '22 23:11

Nathan Tregillus