Reading Rest Api Using Java and Store in String
Table of Contents
- What is Coffee Remainder API?
- Okay, only what is exactly is an API?
- How does this interface work?
- Types of API Requests
- Only what does Rest mean?
- Prerequisites
- Overview
- How to Start Using APIs with Java
- 1. Sign Up for RapidAPI
- 2. Find an API
- 3. Subscribe to the API
- 4. Examination the Endpoints
- 5. Retrieve information using the API
- 6. Get a JSON response
- Example: Using Java & APIs to Brandish other types of Data
- Decision
- Related Resources
- Related Tutorials
- FAQ
- How tin you lot create an API in Java?
- Is Java an API?
- Is JSON an API?
In this article, nosotros will talk about the best technology of the interaction between software and test it on the nearly pop language for creating software.
Browse the Best Gratuitous APIs List
What is Java Remainder API?
This is a tough question so we'll divide it into a few parts. Java is ane of the virtually pop programming languages in the world. According to the TIOBE ranking (which orders languages by their popularity index), it'southward actually the almost popular. There are many reasons for it, just we prefer the thesis that Java is widespread, easy-to-deploy, and has a "write once, run everywhere" magic toolbox.
Are you looking to build an API instead? Check out How to Create an API in Java
Okay, merely what is exactly is an API?
Well, API stands for Awarding Programming Interface.
In short, it's a gear up of rules that controls the interaction between software (i.east., an object that receives some job and object that gives this job). APIs allows u.s. to skip diving deeply in the source code of some third-side software while assuasive us to use their privileges fast and easy.
How does this interface work?
First and foremost, an API should accept a host-URL (or base of operations URL), which is the main address with which you will interact with.
Also, APIs has a predefined set of endpoints – unique addresses inside host-URL, responsible for their functionality. Furthermore, APIs should accept documentation that explains all endpoints, types of returned values, etc.
Subsequently you find an interesting API and read documentation, you lot have to send a request – ane unmarried chore for the server (receiving side).
Metaphorically, it'south like a conversation between two people: Someone (you) asks a question (asking), and the interlocutor (endpoint) answers (response).
Types of API Requests
There are many different types of requests that API could handle, just here are the well-nigh used ones:
- GET – returns data from the server. The most popular request by the mode.
- POST – adds new data on the server. Often this type is used for registration or uploading files.
- PUT/PATCH – updates data, useful request but non so sought-after.
- DELETE – removes data from the server.
Okay, we have got the meaning of the starting time and the last give-and-take in "Java REST API".
But what does Remainder hateful?
This is the style of software communication that helps a client to become the required data in the well-land for representation (Rest – representational state transfer).
So when we say Remainder API, we hateful – APIs that not only returns requested data just likewise prepares it for further work.
Simply how tin can we create a RESTful API? All that is required – a agglomeration of the architectural constraints:
- Customer-server compages – articulate separation on two sides. The customer sends requests and waits for the answer; the server and so takes the opposite role. The chief reason for this constraint – one side doesn't care about anything except the right format of the interaction (it'due south not your problem how the server performs your request and vice versa).
- Statelessness – independence of each singular asking from all previous and future requests. For example, if you would send the question "What Charlie's surname?", and then follow upwardly with "How old is he?", the server wouldn't be able to answer the latter. The server doesn't save any information from the customer and requires it in each request.
- Cacheability – instead of the server, the client could (and fifty-fifty should) save some data on the local storage (cache). It increases productivity, as far as the number of requests volition be smaller.
- Layered arrangement – the server should include layers for dissimilar parts of the process. It is useful considering layers don't know anything almost each other and server could hands be scaled with new layers (eastward.one thousand., security).
- Uniform interface – each endpoint has to be with a unique address. Uncomplicated, useful, and necessary.
At present that we have all the information about Java RESTful APIs, Let's try it out!
Prerequisites
First, you'll demand to take Java installed on your machine.
Also, you should have a Maven package builder for like shooting fish in a barrel installing and using site-packages. Other than that, we will only need the Unirest library for making requests with no issues and in a few lines.
Hither you can wait at the instance of code that makes a request past standard modules:
URLConnection connection = new URL("<some_url>/<endpoint>?param1=value1¶m2=value2").openConnection(); connectedness.setRequestProperty("header1", header1); connexion.setRequestProperty("header2", header2); //Get Response InputStream is = connection.getInputStream(); System.out.println(connection.getContentType());
Looks pretty difficult, correct? Particularly InputStream every bit a type of returned value (it should exist further processed).
Let'southward wait at the same example with Unirest:
HttpResponse <String> httpResponse = Unirest.get("<some_url>/<endpoint>?param1=value1¶m2=value2") .header("header1", header1) .header("header2", header2); .asString(); Arrangement.out.println( httpResponse.getHeaders().get("Content-Blazon"));
Voila! You could assign the expected blazon of response and work with information technology right abroad.
You can use Unirest with the assist of Maven, so create a Java Maven project and find the pom.xml file – it shows all dependencies and tools of the projection. Insert next office of XML code in the <dependencies>
tag:
<dependency> <groupId>com.mashape.unirest</groupId> <artifactId>unirest-java</artifactId> <version>ane.4.9</version> </dependency>
More detailed info well-nigh dependencies may exist found here.
Now y'all can build your projection by next command in terminal (be careful, use it only in the main folder, because pom.xml should exist visible for Maven):
mvn packet
Now you lot're set to for using Java to interact with APIs.
Overview
Before we get started, nosotros'll need to notice an easy API to test. Sometimes it is difficult to find free and useful API for testing purposes. At RapidAPI, you'll detect over 10,000 APIs to test and connect with. Here you tin can test your programming skills, build useful apps, and even create your ain APIs.
How to Start Using APIs with Java
one. Sign Up for RapidAPI
As mentioned before, RapidAPI has over ten,000 APIs to get started with. And with over ane 1000000 developers using its platform, it's one of the most pop and trustworthy API platforms.
And so click hither to get started, it's free.
2. Find an API
Now that you take a user account, let'south find an API to play with.
On RapidAPI.com, yous can find APIs by browsing:
- Categories (case: Gaming APIs)
- Search
- Curated Collections on the Homepage
Let's try searching for the IMDb API to get some info well-nigh Boob tube and movies:
3. Subscribe to the API
To brainstorm using this API, yous'll accept to first subscribe to it. (Hint: there'southward a freemium plan that allows for 1000 free API requests/day). You'll exist required to enter your credit carte du jour in example you incur overages.
If yous want to attempt some gratis APIs (without credit card) instead, browse this collection.
One time yous're subscribed, y'all're at present ready to test the endpoints.
four. Exam the Endpoints
Let's explore all endpoints that are in this API. Look on the left side of the API folio:
The IMDb API has just two endpoints:
-
Go By Search
– search the IMDb database by query string -
Go By ID or Title
– become more detailed information nearly a specific title (includes info nearly the movie/tv, cast, product, and more).
On either of the API endpoints, fill up out any required parameters and click "Examination Endpoint".
On the right side, y'all tin can see the snippet part, where developers show how to connect to this API with whatsoever supported language.
For this API, we need to add two headers (API unique proper noun and our own RapidAPI token). All other params are depending on concrete endpoint. Let'due south explore all endpoints that are in this API. Look on the left side of the principal page.
5. Think information using the API
Okay, be ready, it'due south time for coding. Allow'due south detect out everything about some famous movie that exists within of imdb data. Render to your code and import the next things:
import java.cyberspace.URLEncoder; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest;
Here we import URLEncoder
for preparing params to be sent, and 3 required objects from the Unirest library:
- for handling a response (HttpResponse),
- assigning JSON-type to information technology (JsonNode),
- and making a GET request (Unirest).
Now let's create your master grade, where all the code will be:
public class App { public static void main( Cord[] args ) throws Exception { //Hither will be your code } }
Don't forget about Exception. Y'all should handle all warnings and errors for improving the projection.
Okay, now let's create a few string variables for automating some processes:
// Host url String host = "https://moving picture-database-imdb-alternative.p.rapidapi.com/"; String charset = "UTF-eight"; // Headers for a request String x_rapidapi_host = "movie-database-imdb-alternative.p.rapidapi.com"; String x_rapidapi_key = <YOUR_RAPIDAPI_KEY>;//Type here your key // Params String southward = "Lurid"; // Format query for preventing encoding problems Cord query = Cord.format("s=%s", URLEncoder.encode(s, charset));
Now that we've created the query, let's send a request and handle the response:
HttpResponse <JsonNode> response = Unirest.get(host + "?" + query) .header("x-rapidapi-host", x_rapidapi_host) .header("x-rapidapi-cardinal", x_rapidapi_key) .asJson(); System.out.println(response.getStatus()); System.out.println(response.getHeaders().become("Content-Type"));
As you can come across, information technology's pretty simple.
For creating a request, employ an Unirest library with the GET function.
Pay attending to the headers – nosotros can add together them past using dots for splitting.
After making a request and handling its response past the HttpResponse
object, nosotros tin see the result.
First println
shows the status code of the response – a short number that explains the situation with our requested actions.
In our case, if all is fine, it should render a 200 – OK status.
The 2nd println
, in turn, shows one of the response headers – "Content-Type".
Let'southward encounter what we should go with built-in API panel in RapidAPI. Just input your query in the form fields and click on "Exam Endpoint":
Y'all should see the aforementioned result as seen in the screenshot to a higher place.
Now, let'south check our code. Run your plan, and y'all should see:
200 [application/json; charset=utf-eight]
half dozen. Get a JSON response
In the previous code section, we used a JsonNode
object for assigning JSON format type to the response.
The problem is that default JsonNode object prints data in a single row, which is rather difficult to empathise. Let's add one library for prettifying data – GSON. Modify your pom.xml file with adjacent dependency:
<dependency> <groupId>com.google.lawmaking.gson</groupId> <artifactId>gson</artifactId> <version>2.eight.five</version> </dependency>
Now let's add some import lines in the import section of your *.coffee file:
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonParser;
These objects volition assistance us in pretty-impress our JSON. Okay, now we can call the endpoint and get a response:
// Host, charset and headers vars should exist the same Cord i = "tt0110912"; // Format query for preventing encoding issues query = String.format("i=%southward", URLEncoder.encode(i, charset)); // Json response HttpResponse <JsonNode> response = Unirest.become(host + "?" + query) .header("10-rapidapi-host", x_rapidapi_host) .header("x-rapidapi-key", x_rapidapi_key) .asJson(); //Prettifying Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(response.getBody().toString()); String prettyJsonString = gson.toJson(je); Organization.out.println(prettyJsonString);
If all goes well, we should run into the post-obit response:
{ "Metascore": "94", "BoxOffice": "Due north/A", "Website": "Northward/A", "imdbRating": "8.ix", "imdbVotes": "1,655,375", "Ratings": [ { "Value": "viii.nine/ten", "Source": "Cyberspace Picture show Database" }, { "Value": "92%", "Source": "Rotten Tomatoes" }, { "Value": "94/100", "Source": "Metacritic" } ], "Runtime": "154 min", "Language": "English, Spanish, French", "Rated": "R", "Product": "Miramax Films", "Released": "fourteen Oct 1994", "imdbID": "tt0110912", "Plot": "The lives of two mob hitmen, a boxer, a gangster and his wife, and a pair of diner bandits intertwine in 4 tales of violence and redemption.", "Director": "Quentin Tarantino", "Title": "Pulp Fiction", "Actors": "Tim Roth, Amanda Plummer, Laura Lovelace, John Travolta", "Response": "True", "Type": "movie", "Awards": "Won 1 Oscar. Another 62 wins and 69 nominations.", "DVD": "xix May 1998", "Year": "1994", "Poster": "https://chiliad.media-amazon.com/images/M/MV5BNGNhMDIzZTUtNTBlZi00MTRlLWFjM2ItYzViMjE3YzI5MjljXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_SX300.jpg", "State": "USA", "Genre": "Criminal offense, Drama", "Author": "Quentin Tarantino (stories), Roger Avary (stories), Quentin Tarantino" }
Example: Using Java & APIs to Display other types of Data
Equally you may remember, the Content-Type header of the previous requests was for "awarding/json", but what if we want to ship/receive something that tin't be processed in JSON?
For example, a file or epitome?
Let'due south attempt demonstrating this with the Meme Generator API.
Meme Generator API consists of 5 endpoints:
- Generate meme
- Get fonts
- Upload Image
- Upload font
- Get images
Let's use the Generate meme endpoint:
First, let'southward modify our imports by adding these lines to the top of our code:
import coffee.io.InputStream; import coffee.io.File; import java.awt.image.BufferedImage; import javax.imageio.ImageIO;
At present, paste the following lawmaking snippet inside the principal method:
// Host url String host = "https://ronreiter-meme-generator.p.rapidapi.com/meme"; String charset = "UTF-8"; // Headers for a request String x_rapidapi_host = "ronreiter-meme-generator.p.rapidapi.com"; Cord x_rapidapi_key = <YOUR_RAPIDAPI_KEY>; // Params String meme = "Chuck-Norris-Approves"; String meridian = "Nosotros made this meme with Chuck"; Cord bottom = "Although nosotros weren't even connected to the internet"; String query = Cord.format("meme=%s&acme=%south&bottom=%s", URLEncoder.encode(meme, charset), URLEncoder.encode(elevation, charset), URLEncoder.encode(lesser, charset)); // Meme generator HttpResponse httpResponse = Unirest.get(host + "?" + query) .header("ten-rapidapi-host", x_rapidapi_host) .header("ten-rapidapi-key", x_rapidapi_key) .asBinary(); //Image saving InputStream is = httpResponse.getRawBody(); BufferedImage inputStreamImage = ImageIO.read(is); File epitome = new File("image.jpg"); ImageIO.write(inputStreamImage, "jpg", image); System.out.println( httpResponse.getHeaders() .get("Content-Blazon"));
Here nosotros handle raw trunk of the response into the InputStream
object. Next step is to read it in the BufferedImage
object – dynamic image in the retentivity of the plan.
Finally, let'due south create (or update) an image.jpg file and save buffer inside information technology. This should output the post-obit:
[image/jpeg]
Every bit you may run into, API returns to an image object.
To run into the actual image, let'southward check the chief folder of our project and you should find:
Determination
In this guide, we studied how to utilise RapidAPI for making an heady and useful Java REST API applications and tried a few helpful APIs for clearing fundamental moments in this technique.
- How To Use An API
- With Python
- With PHP
- With JavaScript
- With React
- Axios
- With NodeJS
- With VueJS
- With React
- With Ruby on Runway
- With C#
- in Google Sheets
- How To Create an API with Java
- List of REST API Tutorials
- How to use the Twitter API with Coffee
- How to apply the Skyscanner API with Java
- How to use the Yahoo Finance API with Coffee
FAQ
How tin you create an API in Java?
Cheque out these Java API Tutorials on how to create an API.
Is Java an API?
Java is a programming language.
APIs are a set of definitions and protocols that allow engineering products and services to communicate with each other.
A Coffee Application Programming Interface (API) can refer to the Java development kit (JDK) or APIs that are accessible using Java.
Is JSON an API?
JSON or JavaScript Object Annotation is an encoding scheme that is designed to eliminate the need for an advertizing-hoc lawmaking for each application to communicate with servers that communicate in a defined way. JSON API module exposes an implementation for data stores and data structures, such as entity types, bundles, and fields. – Source
Scan the Best Free APIs List
Source: https://rapidapi.com/blog/how-to-use-an-api-with-java/
0 Response to "Reading Rest Api Using Java and Store in String"
Post a Comment