10) Spring Web Lesson

Prepare for API Interaction with Java and Spring

11 min to complete · By Ryan Desmond, Jared Larsen

In the previous section of this course you learned all about HTTP, web services, and APIs. You used a web browser, Postman, and cURL to send requests and receive responses, helping to build a solid understanding of how web communication works. That hands-on practice was invaluable in preparing you for the next steps. This is a Spring course, and it's time for the good stuff! You are ready to start interacting with the web directly through code, harnessing the power of the Spring Framework.

However, before you can start unleashing hundreds or even thousands of requests for data, there is a bit more setup to do. This lesson introduces the key elements required to start interacting with APIs.

Expanding the introduction for better readability and clarity about the initial steps involved in working with a new API can be approached as follows:

Checking out the API

Each time you discover an API you're interested in using, the first step is to research it thoroughly and learn how to interact with it. This initial research is essential for a variety of reasons, each of which further prepares you to utilize the API in your applications. From a free public API that fetches weather data to an extremely overpriced social media API, getting to know the details beforehand is a crucial part of the development process. Here are some aspects to consider:

  1. Understand the Data Structure:

    • Most APIs these days return data in JSON. You will need to create POJOs that match the JSON structure of data returned from the API, and for most data you want to send to the API.
  2. Access Requirements:

    • Many APIs require you to sign up for access. This might involve creating an account, applying for an API key, or setting up OAuth tokens.
  3. Endpoints and Parameters:

    • APIs offer various endpoints, each serving different functions. You'll need to familiarize yourself with the endpoints you're interested in utilizing, and the parameters that they accept.
  4. Rate Limits and Use Policies:

    • Be aware of any rate limits or acceptable use policies imposed by the API. These can significantly affect how viable an option they are for your specific requirements.

In short, it's important to thoroughly check out the API you want to use before you start coding. This will save you a lot of time and help to avoid potential roadblocks with your integration.

Step 1: Find an API

There are millions of APIs available on the internet. Some of them provide useful data, and some of them are just outright weird. This walk-through uses a simple "Zen Quote" API. It does precisely what the name implies: it provides endpoints to receive various inspirational quotes.

Step 2: Read Documentation (don't start coding just yet)

Most of the time, all the information you need to decipher an API is available on its website. Check out the Zen Quotes website. Here is some key information you want to look out for:

  • Do you need to sign up for access?
  • Do you need an API key to make requests?
  • What endpoints are available?
  • Are there ways of filtering data - path variables? Query parameters?
  • Are you limited in the number of requests you can make?
  • Do they make you pay for more requests? (eye roll)

The Zen Quotes API was chosen for its simplicity - it doesn't require a key or make you sign up. Multiple options are available, but you'll stick with a simple endpoint that returns a single random result.

Step 3: Sample Some Data

With your preliminary research complete, it's time to take a look at what the Zen Quotes API actually returns. You can make a request in your browser, or you can use Postman. As the documentation indicated, requests to the API are made to the endpoint /api/random, which means the URL to hit is https://zenquotes.io/api/random using the GET HTTP method. The JSON returned should look something like this:

[
  {
    "q": "What have you done today to make someone else happy?",
    "a": "Deepam Chaterjee",
    "h": "<blockquote>&ldquo;What have you done today to make someone else happy?&rdquo; &mdash; <footer>Deepam Chaterjee</footer></blockquote>"
  }
]

Beautiful! The JSON above is, in Java speak, an array containing a single object, which contains three String variables.

Step 4: Map Some Data

Now comes the part that is sometimes tedious. When your application receives JSON data, it needs to be parsed. The data should be structured in a "useful" way that is easy to access, process, and manipulate. The most common way to accomplish this is to map the data to a POJO. To make sure the Spring-provided JSON parser doesn't get confused mapping the data from JSON to your POJOs, the JSON and POJOs must match in field names and structure. Depending on the API, this can take some time to set up.

Colorful illustration of a light bulb

Info: As previously mentioned, JSON is not the only format used to transmit data over HTTP. Therefore, you may encounter (on rare occasions) an API that returns a different data format. Spring provides many parsers to deal with this, but figuring out the structure of the data can take more work.

In code, the object represented in the JSON looks something like this:

@Data
public class QuoteTemplate {
    private String q;
    private String a;
    private String h;
}

Which allows the base data (the array), to be mapped to a collection (e.g. QuoteTemplate[]). With this class matching the structure of the returned JSON, the parser can correctly map the data onto the QuoteTemplate class. Remember, this is a straightforward example, and real-world API requests can return hundreds of lines of data that will require mapping. You actually do not need to map all object fields from the JSON response. Say you just want the quote, just simplify the class and the unmapped data will be discarded:

@Data
public class QuoteTemplate {
    private String q;
}
Colorful illustration of a light bulb

Hint: When you encounter a large return structure but only need a part of it, only model the part you need in POJOs. The parser will parse the information it can (the stuff you need) and ignore the rest (the stuff you didn't).

Summary: Java API Setup

This lesson introduced some essential precursor steps for communicating with an API from code and gave a small intro to JSON -> POJO mapping. Here are the steps again summarized:

  1. Find an API.
  2. Check out the documentation/website.
  3. Sample the returned data.
  4. Create matching POJOs.

In the next lesson, you'll actually make the request using Java and Spring!