Help using API's with .getJSON method

Hello,

I’m trying to use an API to get random quotes. I was having issues getting it to work, so I used the code directly from one of the challenges and only changed the ID’s and classes that it is calling from to match my html. Here is the link to the codepen project: https://codepen.io/RyanCarlo/pen/BJwoEg.
My JS code is:

$(document).ready(function() {
  
  $("#getMessage").on("click", function() {
    
    $.getJSON(""/json/cats.json", function(json) {
      $(".messageText").html(JSON.stringify(json));  
    });   
    
  });
  
});

Does anybody know of anything that look wrong or that needs to be added to the settings of Codepen for it to work? I just want to show the object in the message field first.

I have added JQuery and JQuery UI to the page through the JS settings.

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

markdown_Forums

Your link is invalid. When you specify a link like '/json/cats.json' or '/anything', it is trying to get the data from your current project. You need to specify the exact location of the api which is:

https://www.freecodecamp.com/json/cats.json

Now, your link is valid but you run into another problem.

Failed to load https://www.freecodecamp.org/json/cats.json: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin 'https://s.codepen.io' is therefore not allowed access.

freeCodeCamp doesn’t let other websites access their cats API as a security feature. You can work around this, but your best option is to just choose a new API to practice with. You can do this with the Star Wars API. It’s simple and easy to use. Here is an example URL you should GET:

https://swapi.co/api/people/4

If you console.log what you recieve, it should be like this:

{
	"name": "Darth Vader",
	"height": "202",
	"mass": "136",
	"hair_color": "none",
	"skin_color": "white",
	"eye_color": "yellow",
	"birth_year": "41.9BBY",
	"gender": "male",
	"homeworld": "https://swapi.co/api/planets/1/",
	"films": [
		"https://swapi.co/api/films/2/",
		"https://swapi.co/api/films/6/",
		"https://swapi.co/api/films/3/",
		"https://swapi.co/api/films/1/"
	],
	"species": [
		"https://swapi.co/api/species/1/"
	],
	"vehicles": [],
	"starships": [
		"https://swapi.co/api/starships/13/"
	],
	"created": "2014-12-10T15:18:20.704000Z",
	"edited": "2014-12-20T21:17:50.313000Z",
	"url": "https://swapi.co/api/people/4/"
}
1 Like

Also, you don’t need jQuery UI - and if you do include jQuery UI, make sure you link to it BEFORE you link to jQuery in the settings.

Thanks @IsaacAbrahamson! It’s pulling the object up, so I can start tinkering with it.

Just as a general thing, how do you know what links are API’s? I’m still trying to grasp the concepts of JSON, APIs and AJAX.

1 Like

It will become a lot more clear once you get to the back-end yourself, but the understanding will come with practice. A link is just a link - it points/directs to something else. You aren’t going to use a link at random - when you use a URL, you have a specific destination in mind. When I put freecodecamp.org in my browser, I know I will be given a website. When I put https://www.freecodecamp.org/json/cats.json in my browser, I know I will be given JSON data from an api. It’s confusing at first, but whenever you need to use an API, the documentation will be very explicit what URL to link to. As a beginner, it seems like you just put random URL’s in and it magically works as JSON. The truth is that there really isn’t any magic, but your browser is doing a lot under the hood. If you want I can get a little more technical on why a link is an API, but don’t feel like you have to know the specifics quite yet.

Ok, so more technically speaking, every URL points to a server. Server’s deal with requests and responses. Every time you enter a link in your browser, under the hood your browser is sending a request to that server. When the server gets that request, it decides how to answer it, and then sends back what’s called a response. When you just put in a normal URL like freecodecamp.org, your browser sends a request to freeCodeCamp’s servers for HTML data. The server will then send back HTML data in a response. Your browser than parses the HTML and displays it for you to see. Now, when you do something like $.getJSON(...), your browser sends a request to a server, but this time the server asks for JSON data not HTML. When the server gets the request, it will see that you requested for JSON data, so it will retrieve and modify the data you need, and then respond with a json file. So basically, the client or your browser is specific on what type of data it wants. When you load a webpage your browser tells the server it wants to load a webpage, so the server sends HTML. When your browser wants data from an API, it tells the API it wants their data in a json file.

JSON isn’t as confusing as you think. It’s nothing more than a modified version of JavaScript objects. After all, it literally stands for JavaScriptObjectNotation. When you ask for JSON data from an api, the server gives you the JSON data, and then jQuery handily turns it into a JavaScript object for you. It really couldn’t be simpler, because then you can just access the data in the json object like you would any other object in JavaScript.

API is a confusing term. I simplify it this way - it’s a way to access another service. You don’t have full access to Google’s databases. That would be crazy, even if you were an employee. Fortunately, Google let’s us get data from their databases, or interact with them, we just have to do so in a way they give us permission to do so. They give us an API to their services, so when we want to find where something is on a map, we ask for data from the Google Maps API. If you wanted to send a SMS message or text, that would be pretty difficult to just do out of the blue. Forunately, you don’t have to learn how to do all that, because companies like Twilio help you out. They provide a service of texting other’s, and you can use their api to send text messages to others without having to mess with all the details yourself. API’s are a tool. You can get data from other sources like the weather from a weather API. You can use them to access a third-party service designed to help your application.

AJAX is like a design pattern. It stands for Asynchronous JavaScript and XML. Yes, it is also the name of a bathroom cleaner, but we won’t get into that. It used to be that when you loaded a webpage that was it. Your browser asked for a webpage, the server gave your browser a webpage, and it sat there with no contact with the server. Every time you wanted to get data from the server, or send data to the server (like a contact from), or do anything else your page would have to reload. For example, try out this really old website, CNN’s OJ Simpson trial page:
https://www.cnn.com/US/OJ/
Notice how when you click the buttons, it reloads. Every time you hit a button, your browser has to send out a request for new data, and the server will get that data and refresh the page. In other words, it is synchronous. You ask for data, the server sends data, and page is refreshed. Now, take a look at these examples:

https://caferati.me
Notice how when you use the navigation, the whole page doesn’t reload, it just gets the new data and updates the relevant part of the page. This is the usefulness of AJAX - asynchronous getting of data, or in other words you can get data without reloading the page. Instead of building a weather app where you had to reload the page to update the weather, you can now create a website where by clicking a button you can update the weather, change the city, etc. AJAX changes everything, but it’s not all pretty. Because it asynchronous, you now have to deal with asynchronous JavaScript - a huge pain in the butt if you don’t know what you are doing. Fortunatelly, JavaScript has had some great new features added in the last few years and it’s not nearly as bad as before, but when you start out using $.getJSON and similar, you can really get frustrated because your site isn’t behaving as it should. One final thing if you are wondering about the XML in Asynchronous JavaScript and XML. It’s an older form of data that JSON has completly replaced. The name AJAX stucked, but you will be getting JSON data not XML. Ok, enough said. If you want to learn a little more, here are some resources on AJAX:

4 Likes

Thanks @IsaacAbrahamson. This was incredibly helpful! :smiley:

1 Like