Curl and no JavaScript

So as I said in my last story I was giving Free Code Camp a good try. I think I have been learning a lot, especially because of the projects that they give you after all those little exercises. Those projects make you think, a lot. And I probably spent around 2–3 hours figuring out how to use a JSON API.

To the point. The project is to do a Random Quote Generator, in which you would click a button and you would get a new famous quote. This involves finding an JSON API or some sort of Quote database so you can do new requests every time a button is clicked. The toughest part of this project was not finding it, but implementing it with JSON since they do not really explain the magic of jQuery.ajax().

To the code

The most surprising part was that the API site gave examples of implementing in Curl, Java, Node, C#, PHP, and another myriad of languages that did not include JavaScript.

Basically, our lovely API is from Andruxnet found here, and it offers the following Curl example:

curl -X POST — include ‘https://andruxnet-random-famous-quotes.p.mashape.com/?cat=movies' \ -H ‘X-Mashape-Key: Scdxg2N2P1mshTfEFJF87DgxWB3mp1cGxXWjsnOq9Hq21mFLNV’ \ -H ‘Content-Type: application/x-www-form-urlencoded’ \ -H ‘Accept: application/json’

This is messy and I don’t like it. So there must be a way to translate that to JavaScript and use it in our little application, right?

This is were jQuery’s ajax function comes in handy. This basically allows us to communicate with a JSON library and make HTTP POST’s and GET’s.

In JavaScript

This is the basic outline for translating the Curl function:

$.ajax({
url: ‘URL given',
type: ‘GET’,
data: {},
dataType: ‘json’,
success: function(data) {

This is what you do with the data when you succeed.
 },
error: function(err) {
alert(err);
},
beforeSend: function(xhr) {
xhr.setRequestHeader(“Type of Authorization”, "Your Key”);
}
});

So when you throw in our stuff and do a little formatting for the quotes you get:

$.ajax({
url: ‘https://andruxnet-random-famous-quotes.p.mashape.com/?cat=movies',
type: ‘GET’,
data: {},
dataType: ‘json’,
success: function(data) {


$(“.message”).html(‘<blockquote><p class=”text-left”>’ + data.quote + “</p></blockquote>”);
$(“.message”).append(‘<p class=”text-right”> -’ + data.author + ‘</p>’);
},
error: function(err) {
alert(err);
},
beforeSend: function(xhr) {
xhr.setRequestHeader(“X-Mashape-Authorization”, “Scdxg2N2P1mshTfEFJF87DgxWB3mp1cGxXWjsnOq9Hq21mFLNV”);
}
});

And there we go. That way we can successfully call our Random Quote API. Good luck with those Free Code Camp challenges, and check out my Quote Generator here: http://codepen.io/gabrielroacueto/full/vGqEZE/

But don’t cheat and look at my code!

Like what you read? Give Gabriel Roa a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.