What is a REST API?
REST API stands for
REpresentational
State
Transfer
Application
Programming
Interface.
Essentially, this is a communication between the
client (the end user, for example, you!) and the
server. The client
requests a
resource, and the server
responds with a
representation of that resource.
If the client requests an image, for example, of course the server cannot send a physical image, nor should it send the original image file (then no one else after you could see that image because you would have the only copy). Instead, it transfers over a
representation of that image.
When the client makes a request, it gives the server a unique
resource identifier, so that the server knows exactly which resource the client is asking for.
The
API exists on the server. It provides the list of rules for the server and client to follow when they talk to each other. The client might only be able to make certain requests (for example, maybe they're not allowed to POST or DELETE anything to that server), and the API enforces the rules.
We use our browsers to view the internet by making requests to the server. An API exists to allow
programs to make requests to the server. This is a very powerful method of getting data back which you can then use in your own program.
Many companies (Facebook, Spotify, etc) have what are called
publically exposed APIs. Essentially, they want other programs to be able to use some of their data, so they provide a way for individuals and third party programs to connect to their servers and make requests through their API.
Making requests via APIs can be done in multiple programming languages, but depending on your language of choice, structuring the request or decoding the response can take some extra work.
Java VS JavaScript
There's a common joke that Java is to JavaScript like ham is to hamsters. The two languages might have similar names (it's a long story*), but they are very different!
Java is a
class language and uses class inheritance. It's also a
strictly typed language. This means that every variable's type has to be defined at runtime, and the types can't change (so for example, you can't have a variable hold an array, and then later change the value to an integer). This means when programming in Java you must always be careful of what type your variables are and what methods you use on them. On the other hand, it makes for a much more stable program.
JavaScript, on the other hand, is a
prototypal language that uses prototypes for inheritance, and while it has "classes", they're just syntactic sugar. It's also a
loosely typed language, or an
untyped language -- there are types, but JavaScript will happily infer them on your behalf. You can declare a variable and have it hold an int, then a string, then an array -- JavaScript doesn't care. On the one hand, this allows for great flexibility when programming -- you don't ever have to think ahead for what types your variables might eventually hold. On the other hand, you get things like this…
*The short version is, Java was really popular when JavaScript came out, so Netscape decided to piggyback off of Java's popularity and take the "Java" name, and have confused tons of people ever since. Thanks, Netscape!
Consuming a REST API with JavaScript
Prerequisites
- A browser, and some familiarity with Developer Tools
Consuming an API with JavaScript is very simple. You don't even need to use an IDE.
Open your browser, and open up the development tools. Copy and paste the following code in the console, then hit enter:
function getPokemon(name) {
fetch(`https://pokeapi.co/api/v2/pokemon/${name.toLowerCase()}/`)
.then((response) => {
return response.json()
})
.then((pokemon) => {
console.log("Name: ", pokemon.name)
console.log("ID: ", pokemon.id)
console.log("Types: ", pokemon.types)
})
.catch((err) => {
console.log("There was an error.")
})
}
getPokemon('bulbasaur')
You should expect to see in the console window:
Name: bulbasaur
ID: 1
Types: ▶ (2) [{...}, {...}]
If you continue to expand the returned types array, you'll see Bulbasaur has two types, grass and poison.
And that's it! You've made an API call, asked for three pieces of information (the name of the Pokemon, its ID number, and its types) and received a response from the server. You can resubmit this code in your console as many times as you like, changing the name of the Pokemon to see different responses. If you want to see all the information the API will return about your Pokemon (it's a
lot), try adding the statement
console.log(pokemon)
The code above uses a JavaScript interface called the Fetch API. Yes, we just used an API to call an API! While not
technically part of JavaScript, the Fetch API is built into the Window scope (so it's part of the browser), and since JavaScript lives primarily in the browser, no extra work is needed on the programmer's part.
Nowadays, the Fetch API is the easiest API method to use with JavaScript. Earlier, programmers were using
XMLHttpRequest
(XHR) instead, which despite its name can return any type of data and not just XML. However, the Fetch API uses JavaScript Promises (
.then()
), which make the code much cleaner and easier to understand, so most programmers today will be using Fetch.
Consuming a REST API with Java
Prerequisites
- Eclipse is installed
- Maven is installed
- You are using at least Java 11
- Some familiarity with Java, Eclipse, and Maven projects
Create a New Maven Project in Eclipse and Set Up pom.xml
Go to File > New > Other and search for "Maven". Select a new Maven project, and select the "Create a simple project" checkbox, skipping the archetype selection. Name the Group ID and Artifact ID as "rest-api", and hit the Finish button.
Open your
pom.xml
file, and add the following repository:
Ensure You're Using Java 11 Or Higher
First, make sure you have installed at least Java 11. The HTTP API used in this tutorial (just like the Fetch API with JavaScript!) began to be included with Java as of Java 11 and later; the imports will not work if your project uses an earlier version.
By default on Windows, Java will install to
C:\Program Files\Java
, and you should see a folder named something like
jdk-15
. (Java 15 was most current at the time of writing this article.) If you don't have a new enough version installed, go
to the Java SE downloads page and select the newest version.
Once it is installed, or if you already have it, in Eclipse, go to Project > Properties > Java Compiler, and deselect "Enable project specific settings." Next, still in Properties, go to Java Build Path > Libraries. If you don't see
JRE System Library [jdk-15]
(or other applicable version) installed, make sure you go click the Add Library… button on the right-hand side. You should now be using the new Java version for this project if you had an older version installed.
Create Your API GET Class
First, create a package under
src/main/java
called
apiTest
. Then, create a file called
GET.java
.
Copy and paste the following into the
GET.java
file:
package apiTest;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.json.JSONArray;
import org.json.JSONObject;
public class GET {
static String pokemon = "bulbasaur";
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://pokeapi.co/api/v2/pokemon/" + pokemon)).build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenApply(GET::parse)
.thenAccept(System.out::println)
.join();
}
public static String parse(String responseBody) {
JSONObject pokemonData = new JSONObject(responseBody);
int id = pokemonData.getInt("id");
String name = pokemonData.getString("name");
JSONArray types = pokemonData.getJSONArray("types");
return("ID: " + id + "\n" + "Name: " + name + "\n" + "Types: " + types);
}
}
If you run this Java file, you should see an output in the console like this:
ID: 1
Name: bulbasaur
Types: [{"slot":1,"type":{"name":"grass","url":"https://pokeapi.co/api/v2/type/12/"}},{"slot":2,"type":{"name":"poison","url":"https://pokeapi.co/api/v2/type/4/"}}]
A little more work than with JavaScript, but the same ultimate result.
--
SelenaHunter - 11 Oct 2020