How do I structure a real-world API according to REST principles? - rest

We're reworking some APIs and are considering a REST-style approach, but we're realizing we aren't sure how to deal with certain situations (lists of resources with parameters that influence what is selected, etc.), or even how to effectively structure urls for resources that may be referred to by themselves but are conceptually subordinate to some other entity (think users/posts/comments, but with even more complicated relationships).
We've seen a lot of material on structuring REST APIs for simple cases, but what material is available that talks extensively about making these choices in more real-world scenarios?

First, it's important to note here that REST is an architecture, which means that it simply describes a strategy to follow for addressing and working with resources. It doesn't say how to implement that strategy, or even how to tell if somebody's being RESTful or not.
I also think you're overcomplicating things a bit. Here's a more precise answer for your two specific questions:
how to effectively structure urls for resources that may be referred to by themselves but are conceptually subordinate to some other entity (think users/posts/comments, but with even more complicated relationships)
Even if something is subordinate to something else conceptually, that doesn't necessarily matter for purposes of describing it. For example, let's use your blog example. A Blog may have many Articles, each of which may have one or more Pictures. At first crack, you might expect to be able to reference Pictures with something like:
http://api.example.com/articles/123/pictures/456
But notice that, since Pictures are resources themselves, there's nothing wrong with just doing:
http://api.example.com/pictures/456
(lists of resources with parameters that influence what is selected, etc.)
It's perfectly normal and acceptable to have parameters in a RESTful request. For example, say you want to get the first 500 pictures by date, starting from the twenty-fifth such picture. Your API might support something like this:
http://api.example.com/pictures?limit=500&offset=25&order=desc&by=date

If you can be more precise with you questions, there are plenty of people here who will attempt to help.
Otherwise, here are a few other resources that should be useful.
REST Discuss Mailing List
Rest Wiki
REST Cookbook
The best piece of advice I can give you though, is to stop thinking about how to structure URLs and focus on what links you are going to put in your representations. How to structure your URLs will be easy once you have figured out your media types.

I'll go ahead and assume we're talking about RESTful HTTP :)
This is how you would expose a "list of resources with parameters that influence what is selected":
/list?{search part}
Where the search part is some arbitrary string which you use to target a 'section' of the list resource.
The common way to do this (the way that browsers + html forms work) is to have key/value pairs for each parameter i.e:
/list?name1=fred&name2=dave&name3=matt
This convention for arranging your search part is not mandatory but you will find that following this pattern makes it easier to write HTML for your app. It would be no less valid in terms of HTTP and URI to use the following:
/list?fred,dave,matt
how to effectively structure urls for
resources that may be referred to by
themselves but are conceptually
subordinate to some other entity
In REST there is no such thing as 'structured' URIs. A URI is simply a unique identifier - similarities and patterns in URI structure can make organising server side logic easier and make it 'pretty' for users to look at and figure out - but if you're doing REST there is no relationship between the following:
/foo
/foo/bar
.. unless you create a relationship with a hyperlink from one to the other. This rule of thumb is generally referred to as the 'hypertext constraint' or 'HATEOAS'.
Having said that - there's nothing wrong with 'prettying' up your URIs. Just be aware that (if you want to 'do REST') you should be linking everything together. Most APIs expose 'nested resources' like this:
/countries/england/cities/london
Hope that's helpful :-)

Related

Is Rest API naming convention too verbose?

I'm in the process of designing the API layer of one of the research and development applications my company is building. The purpose of the API is to share data from a database and to provide calculation functionalities on our data.
My idea is to build Controller endpoints that follow the classic pattern resources nouns and rest verbs:
GET /api/v1/{organisations}
GET /api/v1/{organisations}/{id}
GET /api/v1/{organisations}/{id}/{offices}
etc.
The developer who's handing me the project strongly suggested that I don't use this convention, he said that companies are moving away from this convention as it is too verbose and, hence, not efficient.
He is suggesting adopting less structured endpoints. Something like this, from the code:
GET /api/v1/{taxEnvId}/covers
GET /api/v1/{coverId}/occupclasses
for example, where the first url could be anything.
I objected saying that it shouldn't change much in terms of efficiency and that the advantages in terms of self-documentation with the design I'm suggesting would be greater than the (in my opinion) very small inefficiency (in terms of bytes sent per request) introduced by a longer path.
He is much more experienced than I am, so I'm wondering whether I am making a mistake in my current 'design'.
Is the classic verb - nouns rest name convention wrong?
Are there any disadvantages I can't see in using that convention?
Is he right stressing on that convention being inefficient?
I couldn't find anyone complaining about that convention on the internet and I'd be happy to listen to other opinions or even redirection to books and links that make my evaluation of this part of the design better.
IMHO your approach seems cleaner and more understandable.
An API must be intuitive and easy to use.
Some links that may work for you:
RESTful Resource Naming
Introduction to REST Endpoints
Best Practices for Designing a Pragmatic RESTful API
Twitter REST API Reference Documentation
I objected saying that it shouldn't change much in terms of efficiency
Since the change is not that different then is it worth arguing over? If he is a senior engineer and the organization wants to try a smaller path approach, then this is an opportunity to help the organization accomplish this goal. If in the end their change to less verbose URL paths leads to no improvement, you can rest assured that you helped arrive to that conclusion. You gotta pick your battles and both URL's look very similar, not really worth arguing if in the end of the day it comes down to opinion, especially when the team already expressed an interest to make the URL paths less verbose.
If you (the company) provides not just data but also functionality in your API, then Rest is a good way to go. Otherwise GraphQL could be a thing, both are fundamentally different.
In short: GraphQL shines if you don't offer buisiness logic.
What I would argue about your approach is the /v1, because that isn't a resource. Versioning is topic on its own.
I find it not very efficient adopting this:
GET /api/v1/{taxEnvId}/covers
GET /api/v1/{coverId}/occupclasses
Just imagine the backing controller. The more types the API has, the more cluttered this controller will become. If that happens, how could this be more efficient or efficient at all?
The urls are short, but urls are cheap.
If he is arguing on bytes being send, introduce him to gzip-compression.

Is REST only adequate for applications with human-computer interaction?

I am fairly new to building applications using the RESTful architecture. As a matter of fact, all I have done so far is categorized as Level 2 REST by Leonard Richardson and that I know Fielding would happily categorize as Non-RESTful.
I have spent hours trying to understand HATEOAS and how to reach level 4. And I see it more clearly now. I conceptualize the application as a series of state transitions, and the resources will dynamically provide links with information on how to move from one state to another.
But everything related to HATEOAS seem to be inherent of a human-computer interaction. I mean, even when the resources provide the links that enable the application user to move to the next state, it is ultimately the user the one that drives the application from one state to the other by causing the use of of the provided links.
But how are things supposed to work when we are dealing with computer-to-computer interaction? After all when it comes to service-orientation the idea of service composition is key, and we cannot naively assume that the client is always going to be a human being? Many services are designed to be consumed by non-human users, and some interactions/orchestrations might be fairly complex, the type of things that are typically modeled with things like BPM, or BPEL.
Is REST and particularly HATEOAS only usable in applications that imply human intervention and if not how is this supposed to work otherwise?
I am getting this vibe that REST is only good for certain type of solutions and inadequate for others, but literature out there has failed to explain those inadequacies and sell REST as the cure of all evil, but I just don't quite get how to use for proper service composition when humans are not the drivers.
I'd really appreciate any references or insights on this, because believe me I have two days straight reading all I have been able to find on this topic and I have not yet being able to reach any reasonable and well documented conclusions.
Well, your client app can parse the response to get possible actions. In this case actual urls are obtained not from knowledge of the API, but upon calling the initial method (usually GET). All human-less.
It sounds almost as if you're comparing SOA to REST/Hypermedia and fail to see that SOA is a strategy, for designing a complex system made out of other systems, while REST/Hypermedia is a software architecture style applying a bunch of constraints on client-server communication. The client, however, can be both a server or a human, it doesn't matter.
To use or not to use REST/Hypermedia is not something to bother with when outlining/designing service composition. It's a question that comes into play when trying to achieve syntactic interoperability. Many times it comes down to comparing REST to Soap and other technical details.

Rest architecture data relations

I am planning the rest architecture of my current project and I want to know which architecture is better. My data consists of users, topics and posts.
So if my usecase requires to get all posts for a specific topic, how should I design it?
I know two approaches:
http://restip/api/topics/:id/posts
http://restip/api/posts/?topicId
So which one is recommended and are there better solutions?
The better way is the first, this link explain all the conventions (Base on ruby on rails conventions).
http://microformats.org/wiki/rest/urls
Is more easy to read a topic with the id have posts.
That's really just a matter of taste. Just be consistant everywhere in your API.
In my opinion though, your second approach is good. It is better to keep it simple by preferring "shallow" URLs (with fewer levels) when possible :
/topics/:topicId
/posts/:postId
/posts/?topic=:topicId
You can add fancy URL rewrite rules later, if needed, so that for example:
/topic/:topicId/posts maps to /posts/?topic=:topicId

Should API REST BDD Cucumbers Gherkins include specific details about an API or data

I'd like to pose this question since it seems to be a point of some debate and I'd like to know the communities thoughts on it.
To give you a bit of background to the way the team I work in operates and give this question some context, we're writing cucumbers for a RESTful API at a session called 'Three Amigos'. Three Amigos basically means there will be a Tech Lead, Developer (one or more) and BA (one or more) involved in fleshing out the acceptance criteria for a story. As part of this session the BA usually drives writing the gherkins for the cucumbers.
Here's an example to kick it off. If I have a RESTful API for getting back information about a car I may have a scenario that says:-
Scenario: Engine size should appear in the car
Given a car exists
When I request the car
Then the car should have a "1700cc" engine capacity
Or you could write it like
Scenario: Engine size should appear in the car
Given a "Mazda/ModelABC" car exists with an engine capacity
When I GET "Mazda/ModelABC"
Then the response should contain "1700cc" engine capacity
Now the first one in my eyes is easier all round to read but will not promote code re-use (is this a big deal?). The second promotes code re-use and is written from the perspective of a stakeholder i.e. a developer but a Business Analyst (BA) would not write it like this so it would make a Three Amigos session fairly pointless.
Given the two approaches which is the more highly recommended choice? I have opted for the first approach in my case but I'm interested to know what the arguments for either method are or if there are some decent articles people can back up the suggestions with that would suggest which approach should really be used.
Thanks.
You can put "IMHO" after every paragraph in this answer. This is my experience after doing BDD / Specification by example for four years.
BDD is about communication.
BDD is about understanding each other in the entire team.
Cucumber is (just) a tool that facilitates communication. The only reason to use Cucumber (and the extra abstractions it adds) is because it will make it easier to understand each other than other formats.
If we were only developers in the team we would probably be better off using code.
So, to answer your question, if your BA's and customers understand GET, POST etc then it might be appropriate to use that in the specification. But beware that you've just tied the specification to the implementation. Changes will propagate even into the Cucumber scenarios.
More likely your first example is format that your customers and BA's can relate to and understand straight off.
But, of course, it depends on the level of technical details your non-technical team members are using. Make it easy for everyone to understand.
BDD is about communication.
Here's some presentations on the subject that I've found both useful and in one case thoroughly entertaining:
BDD as you meant it
Refuctore your Cukes
Cuke Envy

Catalyst best way for url language prefix?

I have already done all the I18N and GetText things in multiple languages for an existing site.
For selecting one language or another it seems that prefixing urls with path parts like www.domain.com/fr_FR/my_action or www.domain.com/de_DE/my_action is the best way to go, gor Google friendly sites.
I have found this module: Catalyst-Plugin-I18N-PathPrefix And seems to be based on this advent article
Is it the right way (or current best practice) to do this in Catalyst?
It promises that I do not need to change my actions, my required arguments and urls.
Or this plugin/technique makes a overload in the server that I can better avoid rewriting all my urls by hand?
Regards:
Migue
Are www.domain.com/fr_FR/my_action and www.domain.com/de_DE/my_action the same resource, just represented in
different languages? Or would your users see different contents depending on the language they choose (like, I don't know, different news)?
If the answer to the first question is yes I'd rather go for implementing Accept-language header compliance, for example using I18N::AcceptLanguage, which has the additional benefit that it won't interfere in any way with how you designed your URLs.
I take the risks and implemented the Catalyst-Plugin-I18N-PathPrefix plugin. It was easy, and the server load (that was my main concern) seems to be unnoticeable.
Lets say... I should use time to optimize a lot of things of my own code before be concerned about the plugin performance.
Thank you, anyway.