I never before worked with API in Ruby on Rails so I'm pretty lost.
WHERE and HOW do I need to put this code.
GET http://api.bigcartel.com/mystore/products.json
Do I need to make a new products model and then write the API somewhere in application.yml
Thanks
There are a few ways you can work with an API from ruby. First if you are lucky maybe somebody already built a wrapper for that specific API. In this case there is one gem but it does not seem to be maintained any more. It might still work so feel free to try it out.
However you can also make HTTP requests by yourself. I prefer to use HTTParty gem. You could define a new class in /lib directory and build an API wrapper yourself, but let's start with a simple example.
response = HTTParty.get('http://api.bigcartel.com/mystore/products.json')
parsed_response_body = JSON.parse(response.body)
So here we first create an HTTP get request, and then parse the body to turn JSON into ruby hash.
Please notice that this is a very minimal example that assumes that everything will always go right. APIs often fail and unexpected things happen, don't forget to catch and handle exceptions that might occur.
Related
I have a Rails app. I'd like to create a route that, in addition to doing some work in the controller and rendering a view, loads some data from another server to include as part of the response. Somewhat like a proxy, but with a bit of logic dependent on both the incoming request to rails and the data loaded from the other server.
Presumably, I'd issue some sort of HTTP request in the controller action, wait for a reply, and then make use of the result.
I'm interested in doing this entirely on the server — I do not want to use AJAX/CORS/etc on the client.
I'm curious as to whether there's a standard, somewhat official way of accomplishing this. I've seen a handful of examples using net/http — is this the "right" solution for the common case?
I'm not particularly worried about latencies, failure modes, asynchrony, streaming, or other advanced implementation details. Once I've got the basics down, then I'll happily layer in other fanciness to address any shortcomings.
Since you are not at all interested in implementing it using jquery or cor, then I think you may like to chose open-uri.
open("http://www.google.com").read returns the whole site as string, then you can do the parsing.
If the site is returning json then parsing will be even easier:
require 'open-uri'
require 'json'
def show
json = JSON.parse(open("https://graph.facebook.com/me/friends?access_token=XXX").read)
#name = json[:name]
#email = json[:email]
end
I have a Ruby on Rails application, and one of its functions is to present JSON data to the user in table form. Before this step, I intend to add a way for users to tweak the JSON data by means of uploading their own Ruby code files that handle this.
This has its dangers. I definitely don't want any form of access (reading or writing) to the databases, nor do I want it to be able to call anything in another file. How can I limit the file in this way?
Essentially all I need is for the main code to call the function in the user-submitted file with the JSON as the parameter, and returning JSON back. All logic during this manipulation of the JSON must happen in and only in the user file.
I've looked around for ways to do this with no luck. I've seen this question:
Restricting access to user submitted code in Rails
The issue here is that I'd prefer an approach that doesn't require a gem. Also sandboxing seems rather complicated for the approach I want, which is a blanket restriction, and not specific things.
I intend to raise the $SAFE level to 4 before calling the user-supplied code/method. That doesn't seem to prevent calling other methods in the application though.
I have a rails application that uses Recurly for its transactions. I am trying to write automated tests for some of the helper functions that I have written.
A super simple example of a function...
def status_for_display
transaction.status.capitalize
end
In order to test these functions, I need to have a Recurly::Account object as well as associated Recurly::Transaction objects.
I have tried going the route of using Recurly::Account.create & Recurly::Transaction.create but I cannot seem to get the transactions to match up with the account.
I am also wondering if it doesn't just make better sense to use the VCR gem to make this happen. In which case, how would I go about doing that? I've never really managed to get VCR setup properly.
VCR is, by in large, plug and play. Once you have it configured and enabled, it'll intercept all HTTP requests and try to play back the data from a cassette. The problem with VCR, though, is that it is request data specific. In order for it to work right, you need to ensure that your tests are always sending the exact same request params to Recurly. You can work around this by having it skip certain things, but it's generally a pain.
The other option is to just use something like Webmock directly and house your own "known responses" for your Recurly calls, but then it's up to you to ensure that you responses stay in sync with the API.
In the end, I'd probably recommend going the VCR route but structuring your tests such that you have known good and bad test scenarios so you can get the real benefits of the cassettes.
I have a web application that also provides an API. The API is fairly simple, so I am just handling it in the respond_to block and returning json if requested. Now I want to version my API. I was looking at versionist gem. This mentions using the api_version method in your config/routes.rb to change routes based on API version. I don't understand this though, since I would think the routes would be the same, but the behavior of the response would change.
My question is, do I need separate controllers for my web and API portions? Also, do I need a separate namespace for the API? Or is there a way to keep things as they are now?
There are some things you'd want to do differently when providing an API. One of them is the ability to set an API version so that you can enhance your API by adding a new version without breaking existing clients. If your API is extremely simple you can achieve this by providing a second set of routes that will include the version. You may use versionist for that. However, when you'll need to add versions, the simplest solution (and the one that keeps concerns well separated) will be to hold a separate set of controllers, and keep them thin so there is no code duplication. This may allow you to use additional gems for the API (e.g. RABL, JBuilder or rocketpants). There are railscasts on each of them, I recommend watching them to get some background on API building.
I'm new to the rails world and am trying to build a app to simply allow me to search things on Amazon and such sites based on the users input.
I've done a little reasearch and it seems the httparty gem is a good place to start? The documents ive found so far though are not the best. They don't really give me a lot of information (where to put the code etc).
Are there any existing tutorials out there or code examples that I can either use or take a look at to give me a better idea of how this thing works?
I'm working on an app like this right now, so let me offer a few thoughts.
First, if you're a complete newcomer to Rails, then as a first step I'd suggest taking a parallel approach to the problem, with two tracks:
Learn about Rails
Learn about how to interact with an API (make requests and parse responses) in Ruby
These are two separate problems, and although you may end up implementing them together, it's best to think about them in isolation first.
For the first one, I'd suggest writing a couple simple apps first to get a feel for how things work. Even only a simple app will require a certain amount of user interaction, possibly saving records to the DB, etc., problems that are separate from consuming data from an API. There are an endless number of tutorials out there on Rails, but just to mention one, you might try Michael Harti's Learn Web Development with Rails as a starting point.
The second point, consuming API data, is distinct from the problems of designing the app itself. To learn more about this aspect of the problem, I'd suggest using a popular API client gem like (as you mentioned) HTTParty, which I use myself. Rather than immediately try to use the HTTParty methods in a Rails app, as an exercise I'd suggest playing around a bit in a console (irb). If you install the gem (gem install httparty) you can then require it (require 'httparty') from the console and immediately make requests and parse responses from the APIs.
E.g.:
irb(main):001:0> require 'httparty'
=> true
irb(main):002:0> response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
=> ...
Once you've got a bit more familiar with Rails and with accessing an API in ruby, then you could move on to actually building the app itself. Depending on how complex your requests to the API(s) are going to be, you have a few options as to how to structure your API requests in your Rails app:
Make the requests part of the Rails app itself, directly from controller actions. This is really only okay if you are only going to support a very limited number of request types (e.g. simple search) on a limited number of services. Anything more complex and your controller will get fat, which is a no-no in MVC frameworks.
Create a separate ruby class (usually called an API wrapper) to group together methods for making requests and parsing responses from the API. With a gem like HTTParty you can do this just by adding a line include HTTParty in the class, which adds the module to the class. There are lots of examples out there on how to do this, here is one.
Use a dedicated gem for accessing specific APIs, or create one (or more) yourself. There are gems for most popular services, e.g. Twitter, Linkedin, Flickr, etc. See this list of API client gems for more. This takes away a lot of the pain of interacting with an API, but will only work for a subset of all services.
You mention you're thinking of using HTTParty, which I can recommend as I am using it myself. There are alternatives such as Faraday (see this list of HTTP clients for more), but I find for most tasks HTTParty will do fine. The documentation may be a bit sparse, but there are a bunch of examples that you can work from.
Hope that helps!