Is it good practice for a web browser to interact with a RESTful API? - javascript

I've been using a couple RESTful APIs for server to server interactions recently and am now thinking about communicating directly with a RESTful API via javascript from within a web browser in my web application.
This would mean using ajax within a web page to talk to my web server using GET, POST, PUT and DELETE requests and the server responding with appropriate http status codes and non-html data (probably json)
Is this generally considered good practice for a web application and why?

It doesn't matter if you are consuming an RPC API or RESTful API from the ajax standpoint, but generally, you can think of a RESTful API as a well-organized, well-namespaced set of remote procedural calls.
Is this generally considered good practice for a web application and
why?
It is useful to do things this way because you don't need to duplicate code in order to have regular CRUD operations across multiple data objects.
Another thing to consider is that if you have a uniform naming convention of API calls that you can write AJAX functions to interact with, you will write and maintain much less code over time in your javascript side of the application, assuming you don't do anything weird in your code.
An example of when / how this would be a good practice would be if you had written a base method designed to automatically determine your AJAX url depending on what you're doing and where you are, and it automatically determines what POST method to use depending on the type of operation... then you literally write one ajax function, and apply it to things rather than write fully separate ajax methods per action item.

Related

Angular and Database Access : Proper Practices

I get the general idea at this point, angular.js is client-side, so any attempts to do database communication is done via initiating get/post requests to a server-side script on the server (via node, php, asp.net, whatever you're using)...
Only thing I haven't been able to determine is what's the proper practice for this in both conventions/security : do you make specialized pages for many of your particular queries, or 1 to a few general purpose pages that run whatever passed in as parameters. That latter option seems like a security nightmare but at the same time making a page for each table's select,insert,update, etc also seems nonviable.
To be clear and try and focus this back to a single question, it feels like I'm missing a concept here. How do you structure the database calls for an angular.js application?
From a security standpoint it isn't very different than a traditional web app. Your web server sends and receives json (most likely) instead of html. This means using something like rails-api instead of full rails. It's best to think of your Angular app as completely disconnected from your web server like an Android or iOS app is.
You might use token based authentication instead of cookies (nothing would preclude you from using token based auth in a traditional web app but I wouldn't say it's commonplace in traditional web apps). Other than that any concepts that apply to securing a traditional web application apply to securing an API.
What database do you use? Structure depends on the app you're building and if DB is relational or not. It's a strategic question, for example it may be better to have nested documents, or not.

JavaScript: Learning how to "consume RESTful APIs"

I've been coding JS for a few years, and am now learning more. Seeing a lot of employers asking for "knowledge of REST APIs" or "experience consuming RESTful services."
I know the basics of AJAX, both in native JS and jQuery. I've done a fair bit 'o goggling on REST, both on SO and the web. There seems to be a ton of info on how to build RESTful APIs server-side with JAVA, C#, etc, but little on how to access those services with JavaScript.
Here are questions:
Is "consuming RESTful services" another way of saying "getting data from a server with AJAX", or something else altogether?
If it is something else, where are some good tutorials on the subject?
Once I get the basics down, where can I find RESTful APIs on the web to consume?
Is "consuming RESTful services" another way of saying "getting data from a server with AJAX", or something else altogether?
No, not at all, but you certainly could consume your own REST API using AJAX. Ajax typically just means xmlHttpRequest, which is inherently a web browser concept. A RESTful API is more like a service interface. In many ways, it's a web service, but without the complexity of SOAP.
Essentially, REST is a way of expressing a transaction or query over HTTP by using verbs and nouns. For example, to get information, you use... wait for it... GET! To put information, you use PUT (or POST, the tutorials below will explain the difference). And to delete something, you use DELETE. It's rather neat. It almost reads like a sentence over HTTP:
GET /users/123
DELETE /users/123
You can guess what those would do.
Because these are just HTTP requests, they can often be consumed using AJAX, however, that is not necessary. In fact, I find REST API's more useful for exposing services or data to other applications, again, just like a web service.
If it is something else, where are some good tutorials on the subject?
It's hard to give a good tutorial on consuming RESTful services because of two reasons:
Each service is different.
It depends on what language / platform you are working in.
Bret's answer mentioned a few good tutorials.
Here is a SO answer which shows a way to consume REST directly in Java: How to consume REST in Java
Here is a reasonable tutorial on how to create a RESTful API using the JAX-RS API in Java and then shows how to consume it: http://www.mkyong.com/webservices/jax-rs/restfull-java-client-with-java-net-url/
I've also had good success with Jersey's REST client. Their REST (JAX-RS) server software is a royal pain (in my opinion), but their client is pretty slick.
I wrote a simple proof-of-concept todo list REST API last spring in Java and the integration tests show good use of the Jersey client to consume the API for testing purposes.
https://github.com/brandonramirez/todo-api/blob/master/src/test/java/com/brandonsramirez/todoApi/TaskResourceTest.java
I'm also a fan of the Unirest client, which is a REST client translated into several languages with a similar interface. They have an Objective-C version, a Java version, a JavaScript / node.js version, a .NET version, etc.
If an employer is looking for experience with consuming REST API's, they probably want five things:
Do you understand the basic semantics of exchanging data over HTTP using the various methods and the design patterns, naming conventions, etc. that go with it along with it?
Do you recognize the de facto standards for mapping CRUD operations onto HTTP requests (like using GET /resources to list all resources, POST /resources to create a new resource, PUT /resources/x to update resource X, etc.)?
Are you familiar with the various HTTP response codes and when/how they would be used? Like can you always assume that a successful response yields a 200 status code? If you create a new resource, is there another commonly used status code (yes, there is)?
Have you actually written any code to consume an existing service?
Can you test a service easily? For example, using curl to create issue an HTTP request very precisely.
And a bonus, but most people don't have a good grasp of this (I struggle to understand its usefulness personally), is hyper-media for versioning by twiddling with the Accepts header.
Once I get the basics down, where can I find RESTful APIs on the web to consume?
All over! Everybody has one! Twitter, Facebook, Twilio, Stripe, Google, Edmodo, Amazon. I could go on forever. In the IaaS world, Amazon Web Services and Rackspace Cloud both offer RESTful API's for managing your cloud infrastructure. For example, I can make an HTTP POST request to a URL that represents my set of servers, and boom, a new server (virtual machine) is provisioned to me.
https://stripe.com/docs/api
https://api.imgur.com/
There are so many that there are even hub services to help consumers find API's and providers to publish them, such as Mashape and Mashery, though the latter appears to be more focused on providers than consumers, judging from their web site.
The github project I posted earlier, with my proof-of-concept, accesses a REST API from Searchly and Twilio so that I can search for tasks, and when one is marked complete, send me a text message, again, all from HTTP requests. However, I used the client libraries from those providers rather than using direct HTTP libraries just to make the code leaner and more focused, without worrying about all of the HTTP plumbing.
For your purposes, hitting a restful API will be very similar to interacting with a server via regular AJAX. The difference is that this API will conform to the restful model, where various CRUD-like operations will conform to REST's particular pattern of using specific HTTP verbs [GET, PUT, POST, DELETE] and also its pathing model of referring to an entity.
Have a look:
http://www.restapitutorial.com/lessons/httpmethods.html
If you want to have a play with a restful API, there's a few frameworks out there where you can spin up your in a few minutes.
I'd probably use Sinatra for this; although there many options:
http://www.andrewhavens.com/posts/20/beginners-guide-to-creating-a-rest-api/
Just google "restful api example [your server-side language of choice]; there's a lot of material out there.
In short order you'll want to explore how cross server side scripting is done with a restful API, and how to use JSONP:
http://www.ibm.com/developerworks/library/wa-aj-jsonp1/

Separating/protecting sensitive business layer logic from client side script in single page app

We've developed some environmental impact calculations and spent a lot of money having them checked and approved by qualified 3rd parties. I'm currently moving our website from traditional asp.net client/server code to a single page application.
Obviously if I was to do the calculations on the client side in script then even if I obfuscated the code with non-semantic variable names, our competitors would be able to reverse-engineer the code fairly easily.
Being somewhat new to all this, my idea is to have the calculations done in asp.net server code called by the same web api that I use for database interactions so I can make async calls which update the relevant parts of the page (via knockout) when the calculation is finished.
Is this the standard/best way to do this or am I completely missing a better way?
Service Oriented approach could be a solution for you.
You can use WCF or Web services for all your calculations (or other services) then using ajax call, bring the result back to the client
So you actually create WCF services and then consume it using client script
Here is a step by step approach to consume a webservice using javascript
http://weblogs.asp.net/yousefjadallah/archive/2010/03/06/step-by-step-how-to-use-web-services-in-asp-net-ajax.aspx

RESTful API communciation from Ruby on Rails (4.0)

We are working on a RoR project implementing an LMS. We need to send data to an external REST service provided by an external server. The data is sent when certain events are accomplished, it is possible that some of those are not triggered by the client (clicks, etc.).
Also, we need to keep consistency in our rails models, because we need to keep record of the user activities.
There is a library provided to work with the API, written in JavaScript. It makes most of the work easy, so we would like to use instead of creating our own implementation for the API requests.
What are the differences between each of the following approaches? Would one be preferable to another?
Use javascripts to send the data, inserting the snippets in the
views, from the client, but having the client execute this might have
some serious implications (scores changed, false success, etc).
Use a NodeJS server to execute the Javascript but we don't really know how to communicate with our main server (Rails)
And finally, use a HTTP client from the Rails app to send the requests to the service. However we don't know exactly how to do it, also there is the question of where this code goes in the MVC pattern.
Option #1, as you've likely realized, is out of the question. For the client to make API calls on your behalf, you would need to send them your secret key/token/whatever you need to authenticate with the API. But once they have that, they could just use a script console to make whatever API calls they want "as you". This would be pretty disastrous.
Option #2 might be prohibitively complex -- I'm personally not sure how you'd go about it. It is possible, using a library like therubyracer, to execute JavaScript code from Ruby code, but there is some degree of sandboxing and this may break code that requires network access.
That leaves you with Option #3, writing your own Ruby library to interact with the API. This could be easy or difficult, depending on how hairy the API is, but you already have a JavaScript version on hand (and hopefully docs for the REST service itself), so combined with something like RestClient or HTTParty the path forward should be clear.
As for where the API calls would fit in your Rails code: If you have models that are basically mirroring the resources you're interacting with through the REST service, it might make sense to add the relevant API calls as methods or callbacks on those models. Otherwise it might be fine to put them in the relevant controller actions, but keep an eye on your code complexity and extract to a separate class or module if things are getting ugly.
(In cases where you don't need to wait for the response from the API before sending something back to the user, you may want to use DelayedJob or similar to queue your API calls in the background.)

General question about javascript (REST vs. SOAP)

I'm calling a webservice currently from the backend. However, the page is taking a while to load and I'm starting to wonder, will the page load faster (in a perceived way) if I use javascript to load the data instead of the backend?
Basically will using a REST service to load the data on the client side make the page load seem faster than loading the data on the backend with a SOAP call? Does page_load fire first or the javascript calls?
In terms of the difference between calling a SOAP service on the backend vs. calling a REST/JSON service on the front end - your page load times may be percieved as faster if you let the frame of the page load, and display a "spinner" when you load the data from a REST service.
Your question is a bit ambiguous since it's not clear that's what you're asking.
Well, REST vs. SOAP isn't really a comparison anyone can make in terms of speed/performance on a website. REST refers to a conceptual semantic model of how to make calls to a service. SOAP, on the other hand, refers to both the semantics of the call, as well as the data format. REST, by comparison, says nothing about the data format (although JSON is typically assumed - but nothing about REST precludes XML or any other data format).
JSON vs. SOAP, however, is a different story.
JSON responses will be easier / faster to parse on the client side than SOAP messages will (assuming you're using standard javascript stuff which works cross-platform, and no fancy plugins).
Load time? SOAP is a LOT more verbose than JSON, and requires additional characters to transmit the same values... so maybe a small delay due to the relative sizes of the messages being sent.
Processing time on the client side? JSON definitely has the edge.
Ease of use on the client? JSON - hands down.
I see this question not as much as a comparison between REST and SOAP, but rather a question about where the service should be called - backend or frontend. Backend code always executes first, before any frontend code, by definition - it just sits on the server, and runs before the response is returned. The javascript runs after the response is returned and the page is loaded.
Steve gave a very good overview, but it doesn't talk at all about backend v.s frontend. Generally speaking there will be no difference in performance or at least no difference that can be predicted. It all depends on the server condifuration and client computers (where the Javascript executes).
The difference (as Steve also mentioned) is in perceived performance. Here, I would always recommend that you call services from the frontend. There are a couple of reasons:
You can display a visual indicator before you call the service to inform the user of the lengthy operation
You can do a partial update of the UI on each next call to the service. If you call the service in the backend, you would have to essentially do a postback (go through the whole lifecycle of your ASP.NET page). This is slow and not visually appealing.
Actually if you are calling a service from the backend I see no point in having a service at all (assuming it only returns data to bind to the UI). You can just use the old Webforms way to construct the UI and return the response directly in your ASP.NET page.
As a conclusion - many of the benefits of web services come when you call them from client script.
Without looking in your code i cant realy say whats wrong/ why is site loading not fast enough.
REST and SOAP are definied standarts for comuniation between client and server.
I prefer REST over SOAP.
The direct answer for your question is: Page_Load event will load before your Javascript background calls. I recommend using javascript with background loading when your page has several web controls that load too much data, draw elements or doing heavy calculations that take much time and affect the user experience and application performance. You need to give the user the ability to load the page and seeing the progress of each element loading (so that he don't get bored while browsing). REST calls with JSON is recommended for this case.

Categories