JavaRush/Courses/JAVA 25 SELF/Learning to work with APIs and tracking the ISS

Learning to work with APIs and tracking the ISS

Open

1. Introduction

Today, almost any modern application uses data from the internet. When you check the weather on your phone, order a taxi, or read the news — that’s always the result of working with an API. Programs “talk” to each other, exchange messages, and most often these messages are simple text — the JSON format.

JSON (JavaScript Object Notation) has become the standard for data exchange between services. Both developers and machines like it: humans can read the text easily, and programs can parse it easily. There are only a few rules in JSON:

  • data is stored as objects (dictionaries) { "key": value },
  • as arrays [value1, value2],
  • or as simple strings, numbers, boolean values, and null.

For example, a JSON object describing a person might look like this:

{
  "name": "Alice",
  "age": 25,
  "skills": ["Java", "Python", "SQL"]
}

We see the keys (name, age, skills) and their values. Compact, readable, and universal.

2. Getting started with APIs

An API (Application Programming Interface) is a “deal” or “contract” that says: if you make a request to a specific address on the internet and provide certain parameters, I’ll return a response in an agreed format.

The address we hit to get data is called an endpoint. It’s just a URL. It often includes request parameters — the so-called query parameters.

For example, this URL returns a weather forecast for Minsk:

https://api.open-meteo.com/v1/forecast?latitude=50.45&longitude=30.52&current_weather=true

If you look closely, the parameters are listed after the ?:

  • latitude = 50.45 — the latitude,
  • longitude = 30.52 — the longitude,
  • current_weather = true — we want the current weather.

Some APIs also require a special “password” — an API key. Then you add it to the parameters, for example & apikey = YOUR_KEY.

You can browse the weather service documentation at open-meteo.com.

3. What does an API response look like?

When we make a request, the server replies with text: a JSON string. Sometimes it’s a JSON object, sometimes — a JSON array.

Example weather response:

{
  "latitude": 50.45,
  "longitude": 30.52,
  "current_weather": {
    "temperature": 21.3,
    "windspeed": 5.2,
    "weathercode": 1
  }
}

Example response from a service with ISS coordinates:

{
  "timestamp": 1717590000,
  "iss_position": {
    "latitude": "48.1234",
    "longitude": "12.5678"
  },
  "message": "success"
}

4. First example: fetching the weather

Let’s write a small piece of code that calls the free weather API at open-meteo.com and simply prints the response to the console.

String url = "https://api.open-meteo.com/v1/forecast?latitude=50.45&longitude=30.52&current_weather=true";

HttpClient client = HttpClient.newHttpClient();
HttpRequest req = HttpRequest.newBuilder(URI.create(url)).GET().build();
HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());

System.out.println("HTTP status: " + resp.statusCode());
System.out.println("Server response:");
System.out.println(resp.body());

Here we:

  1. Create an HttpClient client.
  2. Build a GET request (HttpRequest).
  3. Send it: client.send.
  4. Get a string response: HttpResponse<String>.

If everything works, you’ll see HTTP status 200 and JSON with the weather.

5. Second example: tracking the ISS

Now let’s query the API at open-notify.org, which shows the International Space Station (ISS) coordinates in real time.

String url = "http://api.open-notify.org/iss-now.json";

HttpClient client = HttpClient.newHttpClient();
HttpRequest req = HttpRequest.newBuilder(URI.create(url)).GET().build();
HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());

System.out.println(resp.body());

The result will look like this:

{
  "timestamp": 1717590000,
  "iss_position": {
    "latitude": "48.1234",
    "longitude": "12.5678"
  },
  "message": "success"
}

Right now you’ve received the exact coordinates of the station flying over Earth. If you run this code again in a minute — the numbers will already be different.

6. Helpful details

When you start working with APIs, it’s very important to keep a few things in mind.

First, always check the response status: resp.statusCode(). If it’s 200 — all good. If 404 — the address is wrong. If 401 — you need a key. If 429 — you’re making too many requests.

Second, remember rate limits. Free services limit request frequency so nobody overloads their servers.

Third, JSON won’t always look pretty. Sometimes it’s a long single-line string — that’s normal. Later we’ll learn to add libraries (Jackson, Gson) to parse JSON into fields and work with them as objects.

One more small experiment

Let’s take an API that returns a random cat fact:

String url = "https://catfact.ninja/fact";

HttpClient client = HttpClient.newHttpClient();
HttpRequest req = HttpRequest.newBuilder(URI.create(url)).GET().build();
HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());

System.out.println(resp.body());

Run this snippet several times, and you’ll get a new JSON with a fact each time.

1
Task
JAVA 25 SELF,  12 level,  5 lecture
Locked
Fetching and printing JSON weather response
Fetching and printing JSON weather response
1
Task
JAVA 25 SELF,  12 level,  5 lecture
Locked
Retrieving and printing API response status
Retrieving and printing API response status
1
Task
JAVA 25 SELF,  12 level,  5 lecture
Locked
Checking the server response before printing 🚦
Checking the server response before printing 🚦
1
Task
JAVA 25 SELF,  12 level,  5 lecture
Locked
Retrieving and printing the ISS coordinates from a JSON response
Retrieving and printing the ISS coordinates from a JSON response
Комментарии
  • популярные
  • новые
  • старые
Для того, чтобы оставить комментарий Вы должны sign in
This page has no comments yet