In general, when programming API interactions, should I end the base url with a slash? - httprequest

This question isn't specific to any particular library, framework, or programming langauge, because I expect this to be a sort of generalized rule that has a standard answer across all, or most, programming disciplines.
Imagine I'm writing a class to interact with some Rest api. The rest api has endpoints like this:
POST www.rest.com/item/create
POST www.rest.com/item/delete
POST www.rest.com/schedule/add
GET www.rest.com/schedule/{user-id}
Now, in my class to interact with this api, naturally I'm going to have a base url
private string baseUrl = "www.rest.com/";
And when I want to make a request, I'm going to append the rest of the route to that base URL.
string url = this.baseUrl + "item/delete";
My question is, is it standard to include the slash at the end of rest.com, or is it standard to leave base url without the slash, baseUrl = "www.rest.com", and put the slash at the start of the route, this.baseUrl + "/item/delete"?
I have a feeling there's a universally preferred way, but I can't find it documented anywhere.

Related

RESTful API GET method parameters

We are creating a RESTful API (PHP on apache server) which will communicate with an Android application. Im new for this so excuse me if my question is dumb.
I want to ask for data from the api so I need to use GET method in the request taking into account the semantics. I have to send some additional data to specify what data am I requesting. In GET requests, I cannot send form data fields so how should I attach the data?
Using POST (but this is not semantic)
request header: POST http://example.com/api/v1/serials
request data: date_from=2013.01.01&date_to=2014.01.01&userid=112&is_in=0&starts_with=afx00
using GET and adding url params (I don't know if is this a good practice in a REST API)
request header: GET http://example.com/api/v1/serials?date_from=2013.01.01&date_to=2014.01.01&userid=112&is_in=0&starts_with=afx00
or making well formed URIs with no url params in GET (not sure about this as well.)
request header: GET http://example.com/api/v1/serials/date_from/2013.01.01/date_to/2014.01.01/userid/112/is_in/0/starts_with/afx00
Which one fits the best in the RESTful API architecture? Which should I use and why? Or maybe are there any other options for what I want?
Without question using URL parameters is best. It allows consumers to query for serials using their choice of filters. Your API should support returning results based on UserId alone, or a date range, or both. Or other combinations of inputs that make sense.
Embedding the key/value pairs of the filter in the resource path is an anti-pattern. It's difficult to understand what each path element means, and you would need to contort your routing engine to accommodate additional filter criteria. It also provides no flexibility in terms of choosing what filter criteria to use - you would in fact need to construct multiple resources paths for each combination of filters. And there is the management of ordering each pair (with URL params, ordering doesn't matter). Probably more reasons to avoid this, but those are the first that spring to mind.
Bot GET methods can be used. It is your choise. But I'll prefer using url params. It is easier.

RESTful API,is an .htaccess file with rewrite rules really necessary

Many tutorials that describe how to set up a RESTfull api mention the use of an htaccess file to rewrite the url.
To be honest I do not quite understand where this is useful, at least in my case.
Let me explain.I am building an appointment web app.The user stores appointments in the db-and of course the intention here is that this is done via REST.
The calendar is shown in a page named calendar.php.From the moment the user goes there a GET operation is initiated by backbone to a page named events.php:
var Events = Backbone.Collection.extend({
model: Event,
url: 'events.php'
});
Events.php is suppose to have code related db queries-I say suppose, because I have not written any code there yet.To write the app I am studying this tutorial here.
So here are my 2 questions:
Do you see any need here for htaccess and rewrite rules
The second question is why the url property in the tutorial(the code is found in the section titled Bringing in Backbone ) has as page just events(without the extension)-in that case htaccess would make sense,but why bother at all in the first place
There's absolutely no reason that a "REST" interface to an application should require mod_rewrite or htaccess.
It's generally only useful if you want to retroactively rewrite e.g. old to new URL's (because someone messed up!).
People use mod_rewrite for all sorts of nonsense, sometimes where core pieces of the stack already do it -- for example mapping /foo to /foo.php (mod_negotiation) or by insisting that their implementation read a query string but their URL's look like PATH_INFO.
Backbone models/collections uses AJAX and RESTful resources to get and set data from and to the server. For example collection.fetch() will send GET events.php to get all items. And model.save() will send POST events.php or PUT events.php/1 (where 1 is an ID of the model). Also when you need to get only one particular model data from the server it will send GET events.php/1 (where 1 is an ID of the model). So you may to do not use .htaccess file at all for your simple requests. You can just get and ID from $_SERVER['PATH_INFO'] variable in PHP.

How to return a relative URL from ASP.NET's GetUrlHelper()?

In an ASP.NET MVC 4 website I'm using Web API to return JSON-formatted resources including links for authorized actions (e.g., DELETE). To create these links I'm using the GetUrlHelper() extension method on the HttpRequestMessage...
_httpRequest.GetUrlHelper().Link( routeName, routeValues );
My concern is that the string returned from Link() is a fully qualified URL (it includes the https://example.com/...) when all I think I need is the relative URL (just the /my/resource). Currently, I've got a server problem where our production environment is adding http when it should be https, which doesn't work. I can fix that separately, but it raises the question, should I just supply a relative URL? And if so, is there a better way of getting a relative URL than trimming off the root part of the UrlHelper.Link()-generated URL?
Edit:
After consulting Richardson's & Ruby's meritorious RESTful Web Services, I believe more firmly that a relative URL is wholly appropriate here.
Does the PathAndQuery on Uri help you?
Example: (new Uri(_httpRequest.GetUrlHelper().Link("DefaultApi", new { controller = "Values", p1="abc" }))).PathAndQuery...this would give you like /my/resource?p1=abc

How to use regular urls without the hash symbol in spine.js?

I'm trying to achieve urls in the form of http://localhost:9294/users instead of http://localhost:9294/#/users
This seems possible according to the documentation but I haven't been able to get this working for "bookmarkable" urls.
To clarify, browsing directly to http://localhost:9294/users gives a 404 "Not found: /users"
You can turn on HTML5 History support in Spine like this:
Spine.Route.setup(history: true)
By passing the history: true argument to Spine.Route.setup() that will enable the fancy URLs without hash.
The documentation for this is actually buried a bit, but it's here (second to last section): http://spinejs.com/docs/routing
EDIT:
In order to have urls that can be navigated to directly, you will have to do this "server" side. For example, with Rails, you would have to build a way to take the parameter of the url (in this case "/users"), and pass it to Spine accordingly. Here is an excerpt from the Spine docs:
However, there are some things you need to be aware of when using the
History API. Firstly, every URL you send to navigate() needs to have a
real HTML representation. Although the browser won't request the new
URL at that point, it will be requested if the page is subsequently
reloaded. In other words you can't make up arbitrary URLs, like you
can with hash fragments; every URL passed to the API needs to exist.
One way of implementing this is with server side support.
When browsers request a URL (expecting a HTML response) you first make
sure on server-side that the endpoint exists and is valid. Then you
can just serve up the main application, which will read the URL,
invoking the appropriate routes. For example, let's say your user
navigates to http://example.com/users/1. On the server-side, you check
that the URL /users/1 is valid, and that the User record with an ID of
1 exists. Then you can go ahead and just serve up the JavaScript
application.
The caveat to this approach is that it doesn't give search engine
crawlers any real content. If you want your application to be
crawl-able, you'll have to detect crawler bot requests, and serve them
a 'parallel universe of content'. That is beyond the scope of this
documentation though.
It's definitely a good bit of effort to get this working properly, but it CAN be done. It's not possible to give you a specific answer without knowing the stack you're working with.
I used the following rewrites as explained in this article.
http://www.josscrowcroft.com/2012/code/htaccess-for-html5-history-pushstate-url-routing/

Do REST API URLs have to look like this?

Is it true that to implement a RESTful API, one has to implement a URL structure that looks like this
http://example.com/post/
http://example.com/post/123
where the /123 would be used for edit, delete
Another way to ask the question is: can a URL that looks like this be called RESTful?
http://example.com/script.php?method=get_title&blogid=123
You don't have to design your URI structure like that. It could also be /some_obscure_string/base64_encoded_title/unique_id. This could also be RESTful, depending on several other factors.
But there are several best practices on how to design URIs in a RESTful web application and being as simple and as human readable as possible is one of them.
Your example http://example.com/script.php?method=get_title&blogid=123 could also be RESTful, but the query parameters indicate that some kind of RPC- or RMI-over-HTTP is used instead.
To sum it up: Don't put too much thought into your URI design. This will come automatically with a good and proper RESTful design of your application.
The Idea behind REST is that every resource has it’s own URL and you use the different HTTP methods to interact with those resources. It makes sense to define the URL structure so that the hierarchy between different resources is reflected in the URL, but you don’t have to.
If you have URLs like this
/all-posts/
/first-post
/some-stuff/second-post
/third-post
you still could provide an RESTful API to this. The Idea is that a GET to /all-posts/ returns a list of the URLs of every post object and the client uses those URLs to interact with the resources. Basically the URLs should be treated as opaque data by the client.
As long as the URL that is embedded in the client doesn’t change you also could change the structure without having to change the client.
Your example URL probably doesn’t belong to a RESTful API, since it contains a method get_title. In REST a URL represents a thing. What is to be done with the thing (should it be modified, should it contents be retrieved, ...) is not part of the URL, for that REST uses the different HTTP methods.
A key aspect of REST is that the url is the resource. a uri like
http://example.com/script.php?etc-etc-etc
doesn't put the resource identifier in the resource portion of the uri. that's not to say that a RESTful API shouldn't ever use get parameters; in fact, that's just fine:
http://example.com/posts?sort=date_asc&offset=20&limit=10
might be a great way to get the URI's of the 3rd page of oldest posts. However, using get parameters in this way should only be used in requests where the method is also GET. PUT and especially POST methods should really use simple uri's with the resource that will be affected in only the path portion.
RESTful URI design is all about resources access and they should be structured in the RESTful manner, so you should not have any query strings.
e.g. of GET
authors/
authors/1
authors/1/books
authors/1/books/10
authors/1/books/10/summary
etc.
Anything and everything is called RESTfull these days, just look at some of the responses by it's inventor Dr Roy Fielding and you'll get some ideas. It is worth doing some reading on the subject.
P.S you do not need post,get etc in your URIs, HTTP protocol is at present mostly used for consuming REST APIs and you can pass verb as a part of the call. Also there is a concept of content negotiation i.e you can request any available format from REST API (json,xml atc).
The REST concept is really based on the fact that it is URL driven, and not driven by large data-blobs. With REST, you don't have to pass a giant soap request to invoke a method - your method call/object creation/whatever you want to do is invoked simply by the URL, and the verb you used vs that URL.
Example URLs:
GET http://del.icio.us/api/
GET http://del.icio.us/api/peej/tags/
GET http://del.icio.us/api/peej/tags/test
DELETE http://del.icio.us/api/peej/bookmarks/[hash]
The structure of your URLs doesn't matter. What does matter is that each URL identifies exactly 1 resource. Each resource can have multiple URLs that point to it but each URL should only point to 1 resource.
This can be helpful. Ref:
RESTful service URLs