Finding Luke through the command line by consuming an API
In the last chapter of this series, I need to find a Starwars word related, in the response of an API, a rarely need, yes.
I have to find the word Luke in a known Starwars API, called Swapi, without IDEs, or frameworks but I’ll use the last chapter’s pieces of knowledge
Having the next class:
This StarWarsWordFinder has next specifications:
- Execute a request(GET) to the Swapi(people scope).
- It searches if the API body response would contain my searched word.
To achieve both objectives, I only need the JDK library that contains:
- java.net package that contains:
- URI → to adressing the request.
- http sub-package with:
- HttpClient → to send request and retrieve it response.
- HttpRequest → to build a request.
- HttpResponse → response object.
Getting a similar code like this:
I compile this source to generate a Library as explained in Creating a Java Library chapter, and I run the following terminal command:
Let’s try with Yoda:
Oh! “Forget someone seems the API…”🤣
Let’s try with Vader:
“I’m your API Daddy…” Ok, enough of older StarWars jokes!
Let’s try something else, backing to the code of the library. I could add an external library, to convert API string json response to an object, making it a little more specific in terms of only people’s name scope.
The Gson library could parse the string response to a JSON.
Let’s see the source of StarWarsWordFinder code after adding Gson’s fromJson() method:
It was necessary to create two additional classes:
- StarWarsPeople
- StarWarsPerson
To map the string results to the valid structure.
So, running the following commands:
I get the new version of my library StarWarsWordFinderWithGson then I can run the main class, adding 2 jars, the gson and the starWarsWordFinder libraries:
So, resuming this in a nutshell
- A word needs to be found.
- Identify tools inside JDK library to achivet it.
- Build a java library with it.
- Instance and call it inside our main program.
- Compile it and running it
- Make some starwars boring joke…ok. no.
This is the end of handmade series , I covered:
- Run a Java program with related jar.
- Create a jar.
- Build a service using a known framework.
- Consume an API, create a jar and use it to build a word finder java program.
I hope you enjoyed it like I enjoyed writing it. There are a lot more coming soon.
Tech stack
- Java 11.
- Windows 10.
Repo