Working with APIs in RoR [closed] - ruby-on-rails

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
This seems naive to ask, but seriously I have not seen a resource which explains how to work with an API. The basics. More specifically the procedure to start-up with an API.
There are loads of things in the docs. But how to get it working with an RoR app. Like what variables to put in the db, in the attr-accessible. Or is it even required.
Then parsing it in models. Managing from the controllers and displaying/calling in the view. Dont get me wrong, I do know about RoR, I have made apps, but with API, seems confusing. Need to know all the basics.
Is there any resource which teaches to work with an API.
For my scenario, I want to work with a travel API. What should be the first procedure(after getting the API key).

How you work with an API is largely defined by how that API exposes itself, and what libraries of code you have to deal with it.
Many APIs are presented as HTTP endpoints that you can use CURL, OpenURI, HTTParty or something like that to consume the resource, or deal with the data sent to you, often as JSON or XML.
Here is a list of some of the more popular Ruby HTTP API client libraries at the Ruby-Toolbox.
Pick one of these and write some code that gets an endpoint of that API, then use that data to do whatever you need. Treat the API somewhat like a database.
Codeschool has a cool course that you can start with and do the first few levels for free here:
Surviving APIs with Rails

First, before choosing to work with an API or not, I highly suggest to try to work with REST API since these kind usually adhere to the same structure (there is even a book on REST API) and then you know what to expect.
Lets take a fictional Movie DB REST API example
so REST API is all about resources. Every movie can be created read, updating or deleted (CRUD).
so you know that you have these commands in your disposal - if you want to get a movie in your app you would use the read command that the api supplies. It usually looks like GET /movie/13 (HTTP GET request)
so in your app you would have to insert that line whereever you want it (perhaps in some panel where the user search for a movie and you access the movie DB to get the details of it
so you would have a
def movie_panel
#some stuff
#movie = MovieDB::get(movie_name)
end
so now you have the movie.. now what? parsing it is indeed annoying. luckly most API have gems you can use so they did the parsing for you. Here I used the fake gem MovieDB but if there is no gem you need to query the api yourself, which in this case I advise you to build your own gem, or atleast have a module with some classes and method to make life easier for you. something like
module MovieDB
class Movie
attr_accesor :name, :year, etc...
def initialize(movie_params)
#initizalize the movie attributes from a given movie params
#name = movie_params["name"]
etc..
end
end
end
so in this case you would have your own API wrapper to use. So once you are given the movie params from the external API you can do MovieDB::Movie.new(movie_params) and that will create a movie object that has method (that you need to write) for the functionality that you need in your code.
Inside that module you can handle everything about that API and abstract all that from the core of your app.
so to sum up -
REST API - easy, predictable, managable
non/rest api - make sure there is proper documentation
use what the api gives you as a resource, and ask yourself questions - what do I want from the API? what will I do with the resources (such as a movie, or a facebook page, or a tweet)? Does the API docs say its capable of doing what you want to do with the resource?
as documentation goes, you need to read it to understand what to do. No all docs are clear and not everything is clear on the first reading because you don't know where to start. So start at the beginning - why do you want to API? What does the API promise to do? You need to authenticate? Is there a tutorial? Has someone already made a gem for the API?
take some famous API's and not-so famous API as an example.
Facebook Graph API is very well documented. You know exactly what you get from each command and what to expect. You don't need to write it yourself, since Koala gem have you covered. On the other hand of the API rainbow, lies a Pinterest API, which you might wonder what's it for.. No one knows, because its barely useable, you need to get access to it, and even then its very limited. So if you want to plung in to the Pinterest API, make sure you understand what it gives you and what it doesn't (hint - it doesn't). That's true for every API where it has good docs or bad docs.
Good luck and might I suggest to read http://shop.oreilly.com/product/0636920028468.do and maybe this as well - https://github.com/interagent/http-api-design
Update with the actual API
ok so the api http://www.wego.com/api/flights/docs you wanted is documented quite well
the first thing it says is to get the API rate check
GET http://www.wego.com/api/flights/usage.html?format=json&apiKey=testAPIKey
so right here you can begin to structure your code. You need to save the apiKey somewhere and have a url prefilled with http://www.wego.com/api/flights/usage.html and the parameters are the format and the apiKey
you can create a helper method that does that.
def check_rate(format, apiKey)
...
end
inside you will need to send a request and get the response and parse it something like
uri = URI.parse(#url)
https = Net::HTTP.new(uri.host,uri.port)
req = Net::HTTP::Get.new(uri.path)
req.body = ["format=" + #format, "apiKey=" + #apikey]
res = https.request(req)
and that takes you forward one step. Take the result and parse it. Best in this case is to create a class for this kind of response and add methods such as rate_ok? and such. Basically a Class for each response and instantiate a class per response. The constructor of the class would parse the response and expose whatever attributes you need

Related

Using Siesta with a non-restful API

I know this is probably a long-shot, but is it possible to use Siesta with a completely non-RESTful API? The API I have to work with (and is not in my control so sadly cannot change) requires every request to be a POST request regardless of whether it is purely retrieving data or not.
I've had a read through the question/answer here which gives me a glimmer of hope, however the big difference between that question and mine is the endpoints of each request. For the API I'm using, they're all the same :(
Every single request must POST to /api/api_post.php, and everything else is specified as a parameter supplied in the request.
Obviously I can roll my own request wrapper to handle this, but I'd love to be able to use some of the functionality provided by Siesta and not have to worry about all the annoyances of dealing with networking. Is there any way of doing this at all, or am I out of luck?
You can make your app work with an imaginary REST API, then transform that to non-restful requests underneath Siesta’s nose. (For example, GET /foo/3 might be transformed to POST /api/api_post.php with item=foo&id=3.) It’s a bit of a hassle, but it does get you the benefits of Siesta even for non-REST APIs.
There are two ways to implement this:
Use mutateRequests(…) to rewrite requests. This lets you arbitrarily alter the URLRequest before it’s sent.
Write your own NetworkingProvider. This is a bit more of a hassle, but gives more wholesale control of the rewriting. This approach might be more suitable if, for example, you need to rewrite responses as well, or if you have to turn one virtual request into multiple real ones.
More in the discussion here.

Getting many models in one Rails API endpoint

I'm sifting through a few Rails 5 API tutorials and all the endpoints are as you would expect: /todos for getting all todos, /todos/:id/items for getting a todo item, etc.
I'm building an API where a Site has Tutorials and TutorialItems. I am first wondering if with a Rails API it is possible to create a custom endpoint like /init_tutorials that would get a site's tutorials and tutorial items OR does it instead make sense to have the endpoint /site/:id that would pull Site's tutorials and tutorial items all in one go like so in app/controllers/sites_controller.rb:
# GET /sites/:id
def show
# get #Site.tutorial.tutorial_items
end
Either way is obviously possible. One option is to do have the /site/:id endpoint accept a parameter, something like /sites/1?tutorials=true. This works well for simple APIs but can quickly get out of had for larger APIs with more diverse clients and many potential options.
If you are likely to be doing something more complex you might want to start out using an API style more like Facebook's FQL or Netflix's Falcor API style. There are a few Gems which can help you with either one.

Swagger UI for messaging API

I'd like to know if the following is possible.
Swagger is almost what I need to document a Message based API. For instance for a Command Message I'd like to say "Command" instead of "Post", and instead of "path" I'd like to have the name of the Command.
The spec mentions that Vendor Extensions are possible using "x-" properties but I am 1) not finding any examples of how to do this and 2) not sure if the use of these properties would help me meet my goals.
Might anyone be able to point me to some resources that can help me move along?
Swagger is designed to document REST APIs which are based on HTTP verbs. You can't replace verbs or invent new ones.
Vendor extensions are there to allow adding additional information that the specification does not allow, but ultimately, it is still intended for REST APIs.
From what I gather, you're trying to describe something different.
We do welcome suggestions for additional roads for Swagger (that is, cover non-REST APIs), and in order to do that, I'd suggest opening an issue on the swagger-spec repository.

How to properly use Django (Web and Mobile Deployment) [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
This is a very general and open-topic question. So yesterday we decided we would like to create an iOS app based off our website that is currently being built with Django. Now, Django, like RoR, is suppose to be transparent to the UI; it shouldn't care what UI the user is using. (Proper MVC).
If I look at some of our code for example, here is how we add an equipment into our system:
#login_required
def add(request):
r_user = request.user.userprofile
form = EquipmentFormAdd(request.POST or None, c_id=r_user.company_id, error_class=DivErrorList)
if form.is_valid():
equipment = form.save(commit=False)
equipment.company_id = r_user.company_id
equipment.added_by_id = request.user.id
default_file_path = EquipmentPicture.get_default_file_path()
url_bucket = r_user.company.s3_bucket.name + default_file_path
cell = form.cleaned_data['cell']
equipment.cell_order = cell.equipment_set.count() + 1
equipment_picture = EquipmentPicture.objects.create(
file=EquipmentPicture.get_default_file_path(),
slug=EquipmentPicture.get_default_slug(),
bucket_name=r_user.company.s3_bucket.name,
bucket=r_user.company.s3_bucket, added_by=request.user,
company=r_user.company, url_with_bucket=url_bucket)
equipment.picture = equipment_picture
equipment.save()
return redirect('equipment_index')
return render(request, 'equipment/add.html', {'equipment_form': form, 'company_id': r_user.company_id})
If I look at this, I see that we are rendering straight-away a template and passing it data. This would't work in iOS.
Few questions:
I see a lot of people creating REST APIs. I don't really see the point of doing that if we can just create HTTPResponses with Django. If we were to use something like TastyPie, we wouldn't be able to just create an equipment (like we do right now) with a POST Statement as if you look at our current add function a lot of stuff is done within that function and TastyPie wouldn't be able to call that.
My main question is should we have a REST API running as well as the normal Django server for both the Web and iOS platform, or just have the same functions, with different entry points and renderings according to it?
When do you create a REST API? A lot of our functions when creating and getting data wouldn't work right now with just standard POST and GET calls. Is that bad?
I am kind of confused... sorry for the long question and thanks again!
A REST API is not something different to GETs and POSTs. It's just using them for data instead of presentation. You output JSON or XML instead of markup code. The API consumer then builds the needed user interface to the data.
The real point of a REST API is to take profit of all the tools that HTTP already offers, instead of inventing another layer of encapsulation (like SOAP)
For instance, to indicate the result (success or not) of some action, use the status code. To indicate an action to perform, typically use the verb (get, post, put, delete, head, options). Other request or response metadata will go into appropriate http headers.
This way data is simpler, caching is easier, and integration is easy as pie.
Also, with a good REST API, you could even build a website that uses some JavaScript framework (eg backbonejs) to build UI from data consumed from the API.
UPDATE
So, given the current status of REST things in Django, and having some experience producing and consuming APIs, I'd tell you to build either:
A RESTful API alongside your web, using the same controllers you use for the website if possible. The same web is in fact RESTful, the only difference is that it is not an API. I have tried in some projects to use several libraries to build an API, but always ended up producing my own code for it. Sometime it's easier that way. All client applications (iOS, android, whatever) will use your API, so you can decouple it completely.
If you don't feel comfortable building all the API by yourself, maybe piston can be a valid alternative to tastypie.
ONLY a RESTful API, and rebuild your site using client-side technologies. Why keeping your (few) servers busy producing HTML, when your (many) customers'/users' browsers can do the same work and you don't pay the electricity bill?
In any case a RESTful API will help you to get the data structure of your application well-organized.

good twitter4j documentation

I have been trying to mess with the twitter4j library for some time now, and cannot seem to get it to work.
The web site and documentation there has proven to be less than helpful, and all the resources I have been able to dig up are really old and most likely irrelevant.
Does anyone have any good resources on this stuff (right now, the oauth portion of it)? I am also trying to use this library via Coldfusion, if that makes a difference.
I have been able to create a (what I believe to be) valid request token and url (as I can get to twitter and login), but when I use the tokens that come back to reconstruct an access token later, it always bombs out with some kind of error...
Yes, the official doc is explaining only basic usages.
Twitter4J is best explained at the example codes located in twitter4j-examples/src/main/java/.
And the community is very active and you can expect getting answers promptly.
http://twitter4j.org/en/index.html#mailingList

Resources