How to generate URLs to link back to objects? - spray

I'm trying to build some RESTful services using spray. I've figured out how to build the directives I need. But the issue I'm having is how to reliable generate URLs back to the "resources" I'm working with. Note I use the term "resources" here as it is used for RESTful APIs (i.e. the server side objects one refers to through the API).
I've looked through the documentation and I haven't found any reference for this except mention of "Resources" in the Java sense (i.e. data files in the classpath).
For sure I can build a directive that maps "/items/127" to a resource on the server side. But what I don't see how to do (at least in a safe and automatic way) in Spray is how to generate such a URL given the server-side resource. I'm looking for something similar to url_for from the Flask framework.
For now, I'm writing functions to do this. But, of course, they are fragile because they aren't DRY (i.e. they don't use any knowledge of Spray routing in generating the URLS).
Am I missing something?

What you're asking for is known as reverse routing. As #iwein said, there's no direct support for reverse routing in Spray. You can confirm this from Matthias in this thread. There is an open ticket for this issue.
However, there is an approach, based on the PathMatcher that Marcel Mojzis open sourced which you can find here.
I have a need for this as well, but I'm going to get by with a "known pattern" approach until Spray (or akka-http) comes up with its own solution to this issue. Essentially, I have an object that knows how to generate the URL for certain patterns of things. Each pattern is a function and clients of the object have to ask for the url by one of the function names. Not ideal, but very simple and effective until akka-http provides a more generic solution.

I don't think that Spray has an equivalent of url_for. I don't think it would make sense in the context of Spray, because in Spray you're not annotating functions with urls that map to them, but you're creating routes that deserialize requests and eventually map them to functions.
As such there is no easy way to generate an example url from the name of a function.

Related

Swagger best practices

I am currently defining a Rest API and I intend to use Swagger to document it.
I've already started to define my API specifications with the Open Api Specification in YAML into the Swagger-Editor.
Then, I understand that I will provide that file to the Swagger-codegen to generate a server implementation, and also to the Swagger-UI (whose statics files will be previously paste to my server) to expose the interactive documentation .
According to Swagger, this is the top-down approach.
But later, I will probably need to modify this API, and I want to do it via by this tediously YAML file previously defined, to keep the API easily modifiable by anyone (and Language-agnostic).
Does the way to do this is to modify the definition file and then re-use Swagger-codegen ? By this approach, I guess so that I can't even lightly modify the API directly in the implementation server code without risking to have a out of date documentation.
And If I chose to do the bottom-up approach (via Swagger-core annotation), I will restrain all my further modifications to occur in the implementation server code, and my initial definition file will never be usable again.
So another question would be : Is there a common way to deal with Swagger when we want to modify the API both via the specification file and via the implementation server code (I suppose that the file that Swagger-core can generate me from my code, will never looks like my initial one that I defined by hand).
To maintain the API documentation, the best course of action that i can suggest is to follow a hybrid approach.
Initially, when you have to do bulk development, go for the top down approach. This will reduce the initial set up and coding effort. That's the basic idea behind any codegen.
Then, when it comes to maintaining the APIs, or adding a few new ones every day (or week), follow the bottom up approach. You will already have the previous code, the only thing you'll need to do is add some more annotations or API definitions.
Going for top-down iteratively defeats the purpose of code maintenance. Boiler plates and self generated code are there to give you a quick start, not for sustenance.
My opinion may be biased.
For API client, there should not be a need to customize it in most cases. If you find that you need to customize it to meet your requirement, it may worth starting a discussion via https://github.com/swagger-api/swagger-codegen/issues/new (and also please check what are the options available to customize the output, e.g. for PHP, run java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar config-help -l php)
For server stub, ideally the developers only need to focus on the business/application logic and regenerate the server stub when adding/deleting/updating endpoints (but I don't think all the server stubs can achieve that yet)
Disclaimer: I'm the top contributor to Swagger Codegen

how do websites make their URL's clean (without any file names/extensions) and what benefit comes from it (excluding sexiness)?

www.site.com/site/
instead of
www.site.com/site/index.php
www.site.com/articleName/
instead of
www.site.com/articleName.php
Its been around for so long, but I can't seem to find an article about it anywhere!
I know you can simply do it with directories and index.php files, but I'm sure most sites don't do it that way...
How do these guys do it? And apart from the URL looking nice and clean, what benefits does it gain?
For Apache/PHP mostly (.htaccess) rewrite rules are used. For IIS/ASP sites a URL rewrite module is usually used but there are many other techniques (like: a 'special 404-handler' that handles all non-existing URL's and figures out how to process the request).
Rewrite rules can be(come) very complex or very simple; a rewrite rule can be used for every method (or action) in the url or it can be as simple as passing every request to the same "index.php" (or equivalent) and letting the code handle the rest of figuring out what to do.
Why it's done? Mostly because of SEO reasons or "easy to remember url's" (who types in complete urls nowadays anyways?) or "user friendly url's". You might want to check out this article on wikipedia which also states
The technique adds a degree of separation between the files used to
generate a web page and the URL that is presented to the outside
world.
as a reason and summmarizes some drawbacks and benefits. Even more can be found here.
One way is to use Apache's mod_rewrite module.
I'm sure there are others...
You can use modrewrite on linux, isapi rewrite for iis 6 or 7 or url rewriting module for iis 7.5+.
Search for [friendly-url] here in SO to find dosens of answers.

Which simple REST URL pattern is more common / better?

/controller/action/id
or
/controller/id/action
Which is more common? Which is preferable and why?
Are there any pro's / con's of using one or the other?
Edit:
Or, perhaps to think of this question in a different way, why do most MVC frameworks (ASP.Net MVC, Grails, Spring MVC) default to the /controller/action/id URL pattern? Is there some advantage to this?
Neither of these are RESTful. There should not be verbs/actions in a URL. Those are confined to the HTTP method for good reason (so that clients can interact with your service without knowing anything specific about it).
If you can not do anything except GET and POST, use POST to send an action parameter to /controller/id
Asp.Net MVC uses /controller/action/id. So that is what you'll most often see in that environment. I do not see any technical benefits but simply going with a common pattern can make things easier to understand.
I definitely prefer /controller/action/id. This feels to me more like it is identifying a resource (a noun) rather than identifying an action on that noun (a verb).
In addition to the exact URL to the resource, you need to consider how you are mapping the HTTP verbs. In my experience, we have shuffled the URL around based on what made most sense when combined with the verbs. That said, we also have a couple places we broke the canonical approach for convenience sake (for example, exposing a certain delete action with a GET so that users could perform the action via a browser).
Also take a look at this discussion for more.
REST URL structure advice

Understanding REST conceptually with Rails

I'm a little late to the party, but I'm trying to wrap my brain around how REST is supposed to work, both in general and in Ruby on Rails. I've read a bunch of articles online about this already, but still don't feel like I'm getting the big picture.
REST as I understand it, is a series of aspirational statements, with the net result at the bottom being that URLs should contain all the information necessary to handle a request, and gets should not be able to change the state on the server, and a bunch of other concrete guidelines.
As I understand it, REST in Rails is based around CRUD, which is to say, every model has a create, read, update and a delete action. Each of these actions is accessed through a similar set of URLs, generated by mapping a resource in the routes. So a login URL is creating a user session, so the URL would look like example.com/session/new with a POST, and logout would be example.com/session/destroy with a POST.
What exactly is the benefit of standardizing URLs in this fashion? It strikes me as optimizing for machine readability at the expense of human readability. I know that you could then remap in the routes file example.com/login to example.com/session/new but that is just one more step for no apparent gain to me.
Is it considered really bad practice to develop a website that uses traditional routes now?
Furthermore, each of these CRUD actions should be able to respond to requests with whatever type of response the request is looking for. So the same link to, say, example.com/tasks could also be called at example.com/tasks.xml to get an xml representation of the result, or example.com/tasks.json for a json representation.
Is this to say that a RESTful API would just be the usual links on the site but with xml appended? It strikes me as very strange and awkward that a web API would behave in this way, but this seems to be what's implied by everything I've read. I'm more used to seeing an API that has links like example.com/api/tasks to get the list of tasks. What exactly is the advantage of this approach?
Rest provides another chunk of "convention over configuration." For a widely used, limited set of common problems (crud actions against the models as a whole), rest is very useful as an application development convention.
What exactly is the benefit of
standardizing URLs in this fashion?
Programmer efficiency. Less to think about; enables more time to be spent on harder problems, etc. Better maintainability. Easier testing. Etc.
Is it considered really bad practice
to develop a website that uses
traditional routes now?
Yes, for crud actions that are interacting with an entire record of the model.
Furthermore, each of these CRUD
actions should be able to respond to
requests with whatever type of
response the request is looking for.
So the same link to, say,
example.com/tasks could also be called
at example.com/tasks.xml to get an xml
representation of the result, or
example.com/tasks.json for a json
representation.
Is this to say that a RESTful API
would just be the usual links on the
site but with xml appended?
Yes, if your api fits the rest model. I think the big issue is authentication. If you want your api to be stateless, then you'll probably need to include authentication with each call. At that point, if you don't want to use HTTP level authentication, you'd need to decide how to include the credentials.

What are the benefits of enforcing restful routes in an MVC application?

I've been toying with the SimplyRestfulRouting assembly that comes with the MvcContrib extras, and for the most part I really like that it quickly sets up my routes and leaves me with a good convention to follow in my controllers. However, I'm still trying to wrap my head around REST as it applies to rich internet applications and occasionally feel pigeon holed when I need to do something that falls outside the scope of those 8 or 9 default routes. [Edit: By "pigeon holed", I simply mean I feel like I'm dirtying up the application when I have to create a controller action that is outside the definition of the default "restful routes".]
I heard a comment from a REST proponent in which he stated his opinion that the MVC framework is inherently RESTful, and it got me thinking a bit more about what libraries like the MvcContrib SimplyRestfulRouting are actually buying me.
Not having read a lot about the concrete pricinples of REST, I'm looking for input as to what benefits might come from enforcing such a thing in the context of a forms-over-data, RIA. And with regards to AJAX, how does a RESTful architecture affect my client interaction?
It's likely I'm misunderstanding the use of REST in this context, and would appreciate some StackOverflow mojo to get my head on straight.
The main benefit I can see in enforcing RESTful routes -- regardless of the framework used -- is consistency. You'll always be able to know how the API will work for any resource, which will in effect give you a self-documenting API.
It also provides a wonderful constraint while architecting the application. Rather than having an API with a blank slate that could get complicated very quickly, constraining the routes to the basics will give you guidance as to which resources you'll need to create.
For more of the basic principles surrounding REST, I'd recommend reading this thread.
Being RESTful is more than just having clean URLs.
At an architectural level, REST is about organizing your application functionality in terms of resources, and exposing a fixed and uniform set of CRUD operations on them (e.g. HTTP POST/GET/PUT/DELETE methods). This is known as Resource Oriented Architecture.
In contrast, with Service Oriented Architecture you typically organize application functionality in terms of processes or components, and expose non-uniform, application specific methods on them (e.g. via SOAP).
Note, you can have clean URLs but still end up following non-RESTful SOA design principles.
UPDATE: Sorry, didn't really answer the question, got hung up on use of "RESTful" terminology. If you're just talking about the benefits of clean URLs (REST/SOA argument aside), the typical argument is better SEO optimization and user-friendliness (user can better make sense of and modify URLs).
the advantage is that if you have some adress and from that adress you getting something, then you can call that adress from anywhere you want in you code, and you will get exactly same thing :)
and in concrete example, if you have route that can return some html full with data(user control for example), then you can call it from ajax, from your desktop application or even from your web service...it is very powerfull because you WILL have some functionality repeated over your application...and because some html that you getting from that restful service giving you exactly one view with exactly one functionality, you can call it dynamically from dialog or from page or from your desktop application or from anywhere...
and when you add to this that you can call this adress with parameters, exactly like some method, you can now see how powerfull this can be in creating dynamic pages and web sites/systems
hope this helps

Resources