In SOA architecture should single API do everything or API should be split as multiple action - api

We have an app which is exposing a RESTful API to a UI for purchasing an item. I have a question regarding API design. Lets say the following action should be taken in order
Item to be chosen for purchase
Next give the address to be delivered to
My question is: should we design a single API which gets both data perform both? Or should we design two API calls - one that creates a purchase record and second that update the address to be delivered to?

The recommended SOA approach is to choose coarse-grained services, which would seem to argue the minimum amount of API calls.
However, from a business point of view, item selection and purchase and item delivery are two very different concerns that should be separate components in your architecture. For item selection, you need to consider things like inventory and pricing. For delivery address, you need to consider user address lists, address validation, shipping, and taxation.
Those two components are not likely to interact much except maybe some external association between an item id and address id. For this reason, I'd recommend two API calls. Functionally, this would also allow your API users do things like update the delivery address without re-purchasing an item, send the bill to one address and the item to another address, etc.

As you state that you design a RESTful API you usually start by designing resources instead of the intended calls. Later on, resource representations can be chosen that include other resources for optimised HTTP request counts.
You might want to choose to proceed the following way:
Model the item list resource (GET - lists all items, POST - allows item creation) /items/
Model the address list resource /addresses/
Model the item instance resource /items/item/resourceId
Model the address instance resource /addresses/address/resourceId
Now all of your resources are available you can think about usage patterns. All your resources are generically available and can be mashed up.
Possible approaches to answer your questions would be:
Extend the item instance resource with the needed address details (coarse grained as lreeder stated)
Model a resource /deliverydetails/ as list and instance resource containing item(s) and address, make the deliverydetails to be queried by item id or whatever your use case fits best
Hope that helps!
Btw. you are automatically following SOA approaches with a Resource Oriented Design. Interfaces will be naturally fitting your business requirements and generic enough to support more advanced use cases.
Here is a good example

Related

Asp.Net Core REST API Hierarchical data structure

I have a question regarding how to structure my controllers.
Let's assume I have a have a system that has stores and products and stores have products.
so the way to get stores is /api/stores/{id} and the way to get a product is /api/product/{id} or /api/stores/{id}/product/{id}.
How would you structure the Controllers? should I have a controller for products and controller for stores and every route that starts with stores in it should reside in StoresController otherwise in ProductsController?
This is from Microsoft: Api design guidance
In more complex systems, it can be tempting to provide URIs that enable a client to navigate through several levels of relationships, such as /customers/1/orders/99/products. However, this level of complexity can be difficult to maintain and is inflexible if the relationships between resources change in the future. Instead, try to keep URIs relatively simple. Once an application has a reference to a resource, it should be possible to use this reference to find items related to that resource. The preceding query can be replaced with the URI /customers/1/orders to find all the orders for customer 1, and then /orders/99/products to find the products in this order.

Best practice regarding encapsulation and single responsibility design

I've been developing for many years and a common problem I face is how best to separate out the service layer. I've been using the repository pattern mainly, but I still struggle with this common scenario.
Customer service that returns a single customer.
Invoice service that returns a list of invoices by customer.
The consumer of the service sometimes wants just a Customer other times they want the customer and the invoices which is fine to leave as two calls.
But a new requirement may be they want the Customer, but also want the total number of invoices the respective customer has.
I do not want to corrupt the GetCustomer method and do not want to return a list of invoices and have them do a count (this would work). Is there a best practice without getting into create a lot of one of methods while still keeping performance and round trips in mind? I see a lot of designs where there will get GetCustomer, GetCustomerDeepLoad, etc.
thanks.
It's simple. Don't overthink it.
Services need to meet the needs of the clients. If the client wants customer details, the service sends a representation of customer details and nothing more; if the client wants a customer and all their orders, the service obliges; and so on. In doing so, you might need more than just a Customer object; for example, you might need a CustomerOrderList object made up of CustomerOrderItem, etc.
What you MUST NOT do is mix the concerns of order management and customer management, meaning that the CustomerOrderItem that you return will be a version suited for customer management and not the full-fledged OrderItem that would be modelled for order management.
That's the reason why I have switched to CQRS. Operations (writing/commands) often targets a single entity type while reads (queries) often want a composition of entities.
You dont want to get those queries into the repositories as the repositories tend to get leaky abstractions when you do that.
In your case you can have two types of services: Entity services which are responsible of taking care of changes and query services which are responsible of taking care of supplying information to the client (composition of different entities).
I typically use repositories only on the write side and let the query services query the database directly. That works as you have your business logic contained in the entity services.

RESTfully creating object graphs

I'm trying to wrap my head around how to design a RESTful API for creating object graphs. For example, think of an eCommerce API, where resources have the following relationships:
Order (the main object)
Has-many Addresses
Has-many Order Line items (what does the order consist of)
Has-many Payments
Has-many Contact Info
The Order resource usually makes sense along with it's associations. In isolation, it's just a dumb container with no business significance. However, each of the associated objects has a life of it's own and may need to be manipulated independently, eg. editing the shipping address of an order, changing the contact info against an order, removing a line-item from an order after it has been placed, etc.
There are two options for designing the API:
The Order API endpoint intelligently creates itself AND its associated resources by processing "nested resource" in the content sent to POST /orders
The Order resource only creates itself and the client has to make follow-up POST requests to newly created endpoints, like POST /orders/123/addresses, PUT /orders/123/line-items/987, etc.
While the second option is simpler to implement at the server-side, it makes the client do extra work for 80% of the use-cases.
The first option has the following open questions:
How does one communicate the URL for the newly created resource? The Location header can communicate only one URL, however the server would've potentially created multiple resources.
How does one deal with errors? What if one of the associons has an error? Do we reject the entire object graph? How is that error communicated to the client?
What's the RESTful + pragmatic way of dealing with this?
How I handle this is the first way. You should not assume that a client will make all the requests it needs to. Create all the entities on the one request.
Depending on your use case you may also want to enforce an 'all-or-nothing' approach in creating the entities; ie, if something falls, everything rolls back. You can do this by using a transaction on your database (which you also can't do if everything is done through separate requests). Determining if this is the behavior you want is very specific to your situation. For instance, if you are creating an order statement you may which to employ this (you dont want to create an order that's missing items), however if you are uploading photos it may be fine.
For returning the links to the client, I always return a JSON object. You could easily populate this object with links to each of the resources created. This way the client can determine how to behave after a successful post.
Both options can be implemented RESTful. You ask:
How does one communicate the URL for the newly created resource? The Location header can communicate only one URL, however the server would've potentially created multiple resources.
This would be done the same way you communicate linkss to other Resources in the GET case. Use link elements or what ever your method is to embed the URL of a Resource into a Representation.

User friendly and restful (rails 3)

i am a rails programmer who is on to his 3rd project now (new of course).I am looking for an answer to a general question about Restful architecture. I am sure i am doing something that has a good established answer already.
In restful approach we expose resources but some times this approach feels a little Non user friendly. For example i can expose a product via a show method and then i have another resource called sales that i can expose via product/:id/sales show template to show all sales for a product. But i am taking the user through an extra click here. The ideal will be to show product and all its associated sales on one page itself. But that is a violation of the Restful rule.
I just wanted to ask that are these rules generally broken to make the site user friendly? Being a new comer i dont want to adopt ways that are non ideal so i thought i should ask this question.
Thanks in advance.
Adding in the sales for a particular product would not be breaking any constraints from the RESTful architecture. You have the product ID in the HTTP request so you can just also get the sales for that product. Your separation of concerns should not be affected and you don't need to store a state to get this information. Just extend the model that you return with the view.
It seems like you are more concerned with straying from the convention over configuration that Rails promotes. This extension means that your model will not correlate with only one table in your database, but that is fine. The conventions are meant to reduce the configuration work that you need to do, not restrict your functionality.

designing a restful api: naming URIs, custom headers?

EDIT: I've solved my issues (for now at least).
I've recently been working with the Zendesk REST Api and their use of the custom "X-On-Behalf-Of" header for looking up tickets opened by a particular user got me thinking about Restful Api design choices (in no specific language, more of a how to name URIs question). I've also read this related question on Custom HTTP headers, but it left me with more questions than answers.
Say I have an example restful web service dealing with rental apartment applications where clients use Basic Auth (keep it simple) to authenticate. Define the basic data as such:
Users (can be of type landlord or renter)
Forms (which consist of one or more Document resources and some form meta data like form name and version info)
And then some type of resource corresponding to Rental Applications, which ties together Forms, Applicants (one or more renters), Landlord, and some metadata like status and dates.
I'm struggling to properly model the URIs for the Applications resource in general, and more specifically with respect to a clients role. (assume api root is https://api.example.com/)
How do I allow a Landlord to fetch a list of applications sent to them? My intuition says make a request to "GET /applications" and Basic Auth lets the server know which user to build the list for; likewise "GET /applications" requested by a Renter would return a list of applications they've sent...but I'm not confident this is a solid design in general to mix and match sender vs. recipient lists at the same URI. Should I be thinking about the "/applications" resource differently, and perhaps allowing a hierarchy like "/applications/[USER_IDENTIFIER]" for each user instead?
Also, regardless of my applications URI design, assume a Landlord is able to create an application on behalf of a renter. Is this better accomplished by sending a custom header like "X-Create-On-Behalf-Of: somerenter#example.com" with the PUT/POST creation request? Or should my schema define a field which allows for this alternative scenario.
I'm very much an amateur at this, so I'm open to any criticism of my assumptions/design, as well as any pointers for learning more about designing RESTful api's. Thanks for reading.
I think I've found a solution.
Landlords and Renters are really just subclasses of the same object, which I'll call Party (as in party to a transaction, not birthday party). So then each one has their own resource, named like /party/PARTY_ID.
It's easy to extend this to see that /party/SOME_LANDLORD/applications and /party/SOME_RENTER/applications solve my issues. It also removes my need to consider custom headers.