In one web service written in Rails, I would like to answer with a file along with additional information.
For this, I consider respond with multipart data. How can I send a multipart response with a file and json?
If there is a better way to do this, please let me know. Note that is not possible add the extra data in the file I'm sending.
Extra points for the face of the problem, that is send a file and data at same time. I already accomplished that by doing a multipart request, but if is there a better way to do this, I would like to know.
I don't know exactly what kind of front end you are using and what your browser compatibility requirements are, or you need the webservice for integration with other apps only, but assuming you are communicating with server over ajax and your app is running in modern browser (or you are allowed to use flash plugin), you can return file contents as base64 encoded string as a part of json response. So in rails controller you would have something like this:
render json: {success: true, file: {name: 'invoice.pdf', data: Base64.encode64(#file.read), extra_info: 'some info'}}
on client side you can process that json, get all the metadata you need from it and also let user save the file to their computer. For that you can use flash plugin or native api implementation
This way you can return couple files with any metadata you want with them to user and on client side user can save files if needed. Also, same webservice can be consumed by other applications as long as they can parse json.
try using gem 'curb' or 'rest-client' gem.
https://github.com/rest-client/rest-client
and
https://github.com/taf2/curb
I'm sure you have done some googling already, have you seen this already? It seems like there is a Gem for what you are trying to accomplish, the Gem however seems to be pretty old.
Related
I'm working with a company on lead delivery, and they sent me some info regarding a Ping Post form setup. I've built hundreds of HTML forms processed by PHP (ie. sending an email/etc), but never something that would Ping a url, then return a value. The value it returns is XML.
Here's the purpose of the process:
I send a lead (form data) using the form with a particular zip code
This company parses that info, decides if it wants to "buy" it
Returns XML saying "Approved" or "Denied"
If "approved", I then post the data, and if "denied", I can do whatever I want
What is a common PHP method for doing this? I can research the code and put something together, just need to know what structure or PHP methods would work?
Thanks in advance.
You should be looking into RESTful Web Services.
here's a few examples that might help you
http://markroland.com/blog/restful-php-api/
http://coreymaynard.com/blog/creating-a-restful-api-with-php/
I did not create these examples, just what I found on Google.
I used file_get_contents(url) to handle the posting. The url contains inputs from the HTML form added as a query string, and the response is in XML which gets handled with simplexml_load_file().
As far as I understand your question what you need is to make an HTTP POST request and parse the incoming XML data.
I would rather not use file_get_contents() on remote servers - there are some potential security issues and it was missing some features the last time I checked. I strongly recommend cURL for remote HTTP/HTTPS communication.
Depending on the API you are posting to you might be able to use the SOAPclient class, but from the look of the response you got all you need is XML parser or Simple XML.
Anyway if you just need to check if a certain keyword (like Approved or Denied) is present you can use a simple string matching like this
if(strpos($response,'<STATUS>APPROVED</STATUS')!==false){
//approved
}
...
I just got an API key for a database I wish to access and want to start building my Rails app. However I dont know where to begin with the API key. Specifically I want to use the brewerydb data and I am building an app where users can find the closest brewery to their location. Can anyone tell me how to get started? I am new to Rails and have never used an API before. I don't know where to begin. What file should I put it in, etc... I know I should probably update the GEMFILE, where else?
Thanks!
Check the documentation for the API. That's all I can say. (well... not really: )
Most API's rely on REST or SOAP, which is basically making HTTP request to certain URI's. An example may be
http://api.somewebsite.com/beers.json
Which would return, for instance, a JSON array of certain beers and their properties.
Furthermore, more often than not, you can test API's (that do not require certain HTTP headers for authentication, which makes it harder) by manually constructing the URI's and opening them in your browser. This way, you can verify that your request is okay before you try it in your Rails application an cannot figure out why it's not working.
You should use the 'figaro' gem https://github.com/laserlemon/figaro
It creates a "application.yml" file in which you can add your API key.
I'm trying to understand how webhook works. My understanding is that its the ability to connect two different applications. If I submit a webhook with url
localhost:3000/receiver
to one application, and I have my application with a method
def receiver
end
I was wondering if I don't know what the callback is from the webhook would be, how would I capture data? How do I save any JSON data thats communicating with my application? I was thinking maybe save some file to see what the objects are, but I'm still fairly new and not sure how to capture JSON data?
Thanks
If you are sure that the webhook is returning a JSON, you can so something like this
data_json = JSON.parse request.body.read
Sure, a webhook a is tool to sincronize two apps
You HAVE tou know the structure of the incoming json, because you need to get the info inside
By definition a webhook is sent by POST method, so you can capture it just inspecting the body of the petition, i.e.
webHook = JSON.parse(params[:something])
Your would try with github web hooks and publish your app in heroku, the api is very well documented and there are many examples.
I am pretty new to the Restkit. I know how my restful response will be. Its not ready yet to get from the server side. Is there a way to give dummy input directly to restkit ?
We can give json text file as an input to NSUrlConnection, similarly how to do it here?
I have been able to do this is
- (RKObjectMappingResult*)mapResponseWithMappingProvider:(RKObjectMappingProvider*)mappingProvider toObject:(id)targetObject error:(NSError**)error {
in RKObjectLoader.m
where I optionally read a static json text file and replace the bodyAsString. If you look at
[self.URL description]
you can scan the URL and maybe read a test file based on the request url
How about running a simple web server which will return any output you want in JSON format?
For example, when I need to prototype an app which will use RestKit, I create a simple ruby app using sinatra web framework (few lines of code) and start it locally, and point my RestKit based app to web app (http://www.sinatrarb.com)
I am currently putting together a rails-based web application which will only serve and receive data via json and xml. However, some requirements contain the ability to upload binary data (images).
Now to my understanding JSON is not entirely meant for that... but how do you in general tackle the problem of receiving binary files/data over those two entrypoints to your application?
I suggest encoding the binary data in something like base64. This would make it safe to use in XML or JSON format.
http://en.wikipedia.org/wiki/Base64
maybe you could have a look on Base64 algorithm.
This is used to "transform" everything to ascii char.
You can code and decode it. It's used for webservices, or even on dotnet Serialization.
Hope this helps a little.
Edit: I saw "new post", while posting, someone was faster.Rails base64
If you are using Rails and json and xml than you are using HTTP. "POST" is a part of HTTP and is the best way to transform binary data. Base64 is a very inefficient way of doing this.
If your server is sending data, I would recommend putting a path to the file on the server in the XML or JSON. That way your server doesn't have to base64 encode the data and your client, which already supports HTTP GET, can pull down the data without decoding it. (GET /path/to/file)
For sending files, have your server and/or client generate a unique file name and use a two step process; the client will send the xml or json message with fileToBeUploaded: "name of file.ext" and after sending the message will POST the data with the aforementioned filename. Again, client and server won't have to encode and decode the data. This can be done with one request using a multi-part request.
Base64 is easy but will quickly chew up CPU and/or memory depending on the size of the data and frequency of requests. On the server-side, it's also not an operation which is cached whereas the operation of your web server reading the file from disk is.
If your images are not too large, putting them in the database with a RoR :binary type makes a lot of sense. If you have database replicas, the images get copied for free to the other sites, there's no concern about orphaned or widowed images, and the atomic transaction issues become far simpler.
On the other hand, Nessence is right that Base64, as with any encoding layer, does add network, memory and CPU load to the transactions. If network bandwidth is your top issue, make sure your web service accepts and offers deflate/gzip compressed connections. This will reduce the cost of the Base64 data on the network layer, albeit at the cost of even more memory and CPU load.
These are architectural issues that should be discussed with your team and/or client.
Finally, let me give you a heads up about RoR's XML REST support. The Rails :binary database type will become <object type="binary" encoding="base64">...</object> XML objects when you render to XML using code like this from the default scaffolding:
def show
#myobject = MyObject.find(:id)
respond_to do |format|
format.xml { render => #myobject }
end
end
This works great for GET operations, and the PUT and POST operations are about as easy to write. The catch is the Rails PUT and POST operations don't accept the same tags. This is because the from_xml code does not interpret the type="binary" tag, but instead looks for type="binaryBase64". There is a bug with a patch at the Rails lighthouse site to correct this.