How To Call a REST API In Java - Simple Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we'll walk through how to call a restful api in java we'll go through all the different parts of a rest web service call and how they work then we'll walk through step by step how to code your java programs to create those requests send them and process the results this video is being sponsored by assembly ai so we're going to be using their api as our example they have an api that translates speech to text that's the basics of what it does but it also has a ton of additional features so if you'd like to follow along and code this all yourself along with me just click the link down in the description to create your own account and get your api key it's totally free to get started and do everything that i show in this video you don't even need to provide a credit card or anything like that so go create your account in the link down in the description and follow along so first just what exactly is an api api stands for application program interface all an api really is is a way for two programs to talk to each other in recent years when developers talk about apis they're almost always talking about a web service that can handle http requests that are sent to it do some work and then return a response these web services are called rest services or restful services rest stands for representational state transfer first we'll go over all the different parts of a rest request and how they work and then we'll walk through step by step how to implement creating and sending those requests in java code what we're looking at here is just a simple chrome extension called boomerang that i like to use for testing out rest calls i like to use a tool like this to quickly test new apis before i go and implement them in code so this shows all the different parts of a web service request probably the main part of your request is going to be the url usually all the different services in any given api are all going to be under one common base url for assembly ai the base url to all of their web service calls is this api.assemblyai.com now the rest of the url can vary depending on what we're asking the api to do in that particular call any api that you use should have a ton of documentation about which url you should be using to perform whatever functionality you need just like assembly ai does here for example the first call that we're going to make is to send assembly ai some audio and have them transcribe it into text so we can see here that the url for that particular call ends in a v2 slash transcript so we're going to go ahead and add that to the end of our url here the other thing you'll notice here is this drop down right next to the url that has all these words like get post put delete these are called http methods or sometimes http verbs in general you can think of the http method here as the thing that you want to do and the url as the thing that you want to do that to the main http methods that you'll use almost all the time are these first four here get post put and delete those roughly correspond to your basic crud calls your create read update and delete calls typically you'll use post to create a thing get to retrieve a thing put to update a thing and delete of course to delete a thing and whatever url you use indicates the thing that you want to create read update or delete now if we look at this documentation for the assembly ai api they have this list of supported combinations of http methods and urls each one of these supported combinations is called an endpoint now if we scroll down here to the endpoint that creates a transcript we can see that the http method that we want to use is a post so let's go back over here and select post for our http method so this transcript is the thing that we want to operate on and since we're sending a post we're saying we want to create this thing we want to create a transcript the overall gist of this first call is we're going to send assembly ai an audio file and it will create a text transcript for us now the next element of a request to a rest api is the request body not every request will have a body but many will the body will contain basically any information that the api needs to perform the logic of the request 99.9 of the time you'll be writing your request bodies in json if you're not super familiar with json don't worry much about it what we're going to do with it here is pretty simple and straightforward the documentation for any api endpoint that you're using should tell you exactly what is required to send in a request body and then also what optional things you can send if you want for example in assembly ai's a post transcript endpoint it lists all the parameters that we could send in the request body here and there's quite a few of them however only one of them is listed as required and that is this audio url here and that kind of makes sense right the one thing you definitely need in order to create a transcript of some audio is the audio most api documentation will also have an example of a valid request body like this one here this shows what the most basic successful request to this endpoint will look like and it only includes the one required parameter the audio url of course if we want we can customize our request by messing around with all of these different optional parameters that the api offers and i encourage you to go through the documentation and play around with that but for now we're just going to keep it simple and copy this most basic version of a working request that they provide here but we are going to replace their audio file with our own so let's go ahead and copy this request and then back here we have to choose the body type that we want to use and for us we want to use json and then we just have to paste in our json request here in the text box but i'm going to replace the value of this audio url with the url of our own audio that we're going to be using so here's the audio file we're going to be sending to assembly ai to transcribe for us these pretzels are making me thirsty yes i am a nerd feel free to use this audio file yourself to test your own calls the link to the audio file will also be down in the description the last part of a rest request that we're going to look at is the headers headers are where you can include various kinds of metadata about the request so that could be like any credentials that you need to send to prove to the api that you are who you say you are or information on what kind of response we want to get back things like that i'll go ahead and click add header here so headers are just key value pairs just like a map in java so it's just the name of the header and then whatever value that we give it for this api there's just one required header and it tells you about it at the very first page of the walkthrough so it says authentication is handled via the authorization header and the header should be included in all your requests and the value of that header should be your api token and you'll see a similar kind of setup with basically any api that you use so when you create your assembly ai account in the link down in the description they'll give you your own api key and you can find it right on the landing page after you log in here your api key is something that you always want to keep private so don't give it to anyone don't share it and don't accidentally put it in a youtube video i'll be blurring it out or putting in a temporary fake one whenever i show it because i don't want anybody else to use it so to add a header over here just go ahead and put the name of the header that you want here which is going to be authorization and then the value here which is going to be your api key okay so now we've got all the elements of our request in place we've got the url the http method the body and the headers now to send the request we just hit send so here we go okay so here is our response over here on the right the first thing we want to note is the http status code of the response and that's what's shown here so here we received a 200 status code there are a whole bunch of different status codes that you'll come to memorize over the course of using various apis but there's only a few things you need to know about them to get started the one that we received a 200 basically means your call was successful your request was good and the api was able to do what you asked it to do you'll typically see only two other main categories of response codes and they both indicate failure and those are 400 and 500 level responses a 500 level response means something went wrong with the api on the server side it's not your fault and there's nothing wrong with your request that doesn't happen too much on good professional apis and i haven't gotten a 500 for any of these calls i've made with assembly ai but it's good to be aware of that on the other hand you have 400 level responses which basically means there's something wrong with the request that you're sending for example you're probably familiar with a 404 which means that the end point that you're trying to hit doesn't exist there are other 400 level status codes that you might see in response to but basically they all mean something is wrong with the request that you're sending the response will also have headers just like the request does for example it's telling us the time stamp that it responded it's telling us that the body of the response is going to be in json stuff like that there are some situations where you might have to look at the information in a response header but honestly not too often but it's just good to know that they're there finally we have the body of the response now typically when you get a successful response to a post call which is supposed to create a new resource the body of the response that you get will be a representation of that resource at that time so we told it to create a transcript and it responded with the current state of the transcript we had it create you might expect that it would immediately respond with the full entire text of the audio file that we had it process but for this request it's going to be a little bit different because it's going to take a bit of time for assembly ai to fully process the audio file that we sent especially if it happens to be a very large file now if we look over here in the documentation it says that when we submit a file for a transcription the status will start with cued and then go to processing and then finally completed when it's done creating the transcript now this status that they're talking about refers to this status element that we see in the response body so right when we sent the request it cued our audio file to be processed and at some point after that it's going to complete and is probably already complete now so now in order to go and retrieve that completed transcript we're going to need to send one other request but luckily it's a very simple one so what we need to do now is get the current state of that resource again which should be the completed transcript now in order to get a specific transcript from assembly ai we have to identify it in some way notice that in the very first line of the response here is an id this id uniquely identifies this exact transcript so what we're going to do is create one other request starting as a duplicate of this first one but instead of sending a post to create a new transcript we're going to change this to a get so we can retrieve the current state of a transcript that has already been created now the way we get a specific transcript is by its id and all we have to do is put that id in the url right after transcript so it'll be transcript slash the id of the transcript that you want for this call there's no request body needed at all so we can just get rid of it and as for the headers it's the same as before we'll be sending our api key in the authorization header as is required for every call and that's it so let's go ahead and try it and see what we get all right so now we see that the status here instead of being queued it is now completed so this is the full transcript for that audio now there are a ton of really cool features in this response that you can play around with and i really encourage you to do so but the main part of it that you're probably interested in is this text element this text element is the string that contains your fully transcribed text for the audio you submitted pretty cool right so now that we know all the different parts of a rest api call and how it works and specifically how the assembly ai api works let's walk through exactly how you can create and send these requests in java okay so this is just a regular main method in a java project where we're going to code our rest call we're going to want to use some kind of a library to help us create json requests unfortunately there aren't any of those built into java so you're going to have to include it in your project the one i like the most is called json it's made by google and it's crazy easy to use if you're using maven the dependency for json looks like this okay so we need to make two calls right first is the post in order to have assembly ai create the transcript and then the get call to retrieve the completed transcript so let's work on the post request first so all the elements of our request the url the http method the request body and the headers are all going to get put into one object called the http request we'll go ahead and name it post request just to differentiate it from the get request we'll create later and we'll initialize this request with a call to httprequest dot new builder this uses the builder pattern so we can add all the different elements of our request in a chain of method calls first we'll call dot uri to set the url that we want to use for our request this method technically takes a uri object instead of a string but it's easy to create that object just by calling new uri and then passing in the string of the url that you want to use so let's just go back over here to our post request copy that url and paste it in here next we want to add the authorization header with our api key to add a header here you just need to call dot header now this takes two parameters the first parameter is just the name of the header that you want to pass in so for us that would just be authorization and the second parameter is the value that you want for that header so for us that be your api key now of course i don't want to give away my api key so i'm going to be creating it in a separate file and a string constant and just using that constant here there you go this is my api key if you want you can just go ahead and paste in your api key if you're working on the project yourself not a big deal next we have to tell it which http method that we want to use which will be post and also what we want our request body to be now to say that we want it to be a post we just call dot post now what this post method takes as a parameter is a body publisher now that's kind of a weird name but luckily it's pretty easy to use so if you want to send in a json string as your request body you just have to use body publishers string and then here you'll actually pass in the string of the json that you want to submit so if you want you can just go back here to your post request and copy the body that we used and paste it directly in here and that'll totally work but there's a better way to do it that'll make your life a whole lot easier in the long run and that is using json now back here just take a look at this request body remember that we're posting a transcript right we're saying hey assembly ai i want you to create a transcript and here's the current representation of that transcript object that i want you to create and the body of this request represents the current state of that transcript object which to start is just the audio url that we want it to use so this request kind of looks like an object of a transcript class that has an audio url string as its only field right now and actually that's exactly how we can create our json request in our java code let me show you what i mean so we can go back to our java project and create a new transcript class so public class transcript now this class will correspond to the request body the transcript that we're posting in our post request right now for this request the only thing we need in that transcript class is this audio url for this to all work correctly though using json we have to use this exact name as it is in the request so back here in our transcript class we're going to add a private string audio url and then we'll go ahead and generate our normal getters and setters then what we're going to do is create an object of this class and then we're going to have json do its magic to automatically translate that object into a json string exactly like this that we can use for our request so back over here in our main code we can create an object of that transcript class so transcript transcript equals new transcript and then we're going to set the audio url on that transcript object to be the audio url that we want to post so we'll just go back here and copy this same audio url and paste it here now here's how you use json to translate this object into json first you have to create a new json object so json json equals new gson and then all we have to do is call json.json and then pass in to this method the object that we want to translate into json so we'll just pass in our transcript object so let's go ahead and save this json string into a new variable we'll just call it a json request and set that equal to the result of that method call and we can go ahead and print out this json request just so we can prove to ourselves that it's working let's go ahead and comment this part out for now just so we can run this and make sure that it's properly creating our json request string okay so here's the json string that json is creating for us and it looks perfect and that's automatically created from this transcript object and we didn't have to do any fancy weird string parsing or anything like that all we had to do was call json.json pretty cool so now we can go back and uncomment these lines and then we can go back here and plug in our json request variable and then to finish off this post request object we just need to call dot build all right so now our request is ready to send how do we do that well we're going to use the http client library for that so first we'll create a new http client object we'll call it http client and we'll initialize it to httpclient dot new http client then in order to send this post request all we have to do is call http client dot send and then we need to pass in the post request that we want to send we also have to pass in something that tells it that we're expecting a string response as well and we'll do that by passing in body handlers dot of string again kind of weird but it's just how we tell it that we expect it to send a string in response now we can store the response that we get back from sending this call in an http response object so we'll create an http response of type string because we're going to get a string back in the response and we'll just call it post response now we can get the actual body of this response just by calling a post response dot body so for now let's go ahead and print out the body of the response that we get and give it a test and here we go there's our request and there's our response so awesome that worked here's the id of our transcript and a whole bunch of other information including the status which starts out as cued so everything's looking good next we just have to put together our get call and then keep sending that get call until assembly ai is done processing the audio first remember how in the get call we have to submit the id of the transcript that we want to get at the end of the url well right now that id is in the response to our post call but it's just in here you know inside the json string and we don't really have a good way to grab it so how should we go about doing that basically what we want to do is the reverse of what we did when we created the request so when we created the request we had a transcript object and we wanted to translate that object into a json string here we want to go the other way and we want to take this json string and translate it into an object often you'll need to create a whole separate class for the response that's different from the one that you needed for the request but in this case the response that we're receiving also represents the current state of the transcript object that we're creating so we can actually use this same transcript class and just add this id field onto it so let's go back to our transcript class and just add a private string id and we'll add getters and setters for that as well okay so now we just have to convert this response json that we received into a transcript object and we'll do that similarly to how we took an object and turned it into json so we actually called json dot from json now this method takes in two parameters the first of course is the actual json string that we want to convert into an object the second parameter is the class that we want to convert this json into so for us that would be transcript.class so next we can just assign our transcript variable which we already have to be the result of this conversion and now at this point we can get the id of that transcript off of this object just by calling transcript dot get id so now that we have the id let's construct our get request let's go ahead and start with a copy of this post request because a lot of it is going to be the same of course we'll change this to get request of course we'll change this post to a get now our get request doesn't need any request body so we can just get rid of that if we want and actually for this http request get is the default if we don't specify anything so if we want we can just go ahead and get rid of that completely the authorization header is exactly the same so we don't have to change that but we do have to change this url a bit remember that we have to append the id of the transcript that we want to get to the end of this url here so we'll just do plus transcript dot get id now we can actually send this get request and store the response in pretty much exactly the same way that we did with the post request so let's go ahead and copy this code that sends the post request but of course instead of a post response we'll have a get response and we'll be sending the get request we still want to use bodyhandlers.upstring here because we still expect a string in response to our call and the response that we receive from this get call is also a transcript so we can even store it in the same object here the same transcript object so down here we'll just be calling json.from json and passing in our get response so it'll take the body of the get response and translate that into a transcript also and store it here in this variable now remember though the first time that we send this get request it might not be done completely processing the audio and remember we can tell whether it's done or not by looking at this status in the response so what we're going to want to do is add this status into our transcript class so private string status while we're in this class though remember that when everything's completed the main text of the transcript is going to be in this text element of the response so while we're here let's go ahead and add that text field also so private string text and then again we'll go ahead and add our getters and setters okay so now that we've added these two fields json will automatically populate those fields on this transcript object correctly when it converts from the json string so anyway what we want to do is keep sending this get request over and over again until the response that we get back has a status of completed meaning that it's fully processed the file and the transcript is done or the api could also return error for this value if there's some kind of a problem processing the audio for example if maybe we sent in a bad url or something like that but anyway once it's completed then we can print out the text that it returns so let's go ahead and put the sending of this get call inside a while loop so we can keep sending it over and over again until it completes so we'll just do a good old-fashioned while true and put all of this code inside that loop now after we make the call each time let's go ahead and print out the value of the status that we get in the response so we can track it from going from queued on to processed and then finally being completed next we can check the value of the status to see if it is either completed or error and then break out of the loop if it is so that would be if first we'll check for completed so if completed dot equals transcript dot get status or error dot equals transcript dot get status so if the status is either one of those then we want to break out of our while loop so if it doesn't break out of the loop here that means it's still processing and we're going to make another get call over and over again until it's either completed or runs into an error but let's go ahead and have it wait for just one second before it tries again and there are fancier ways to have it wait for one second but for our purposes it's simple enough just to call thread.sleep for 1000 milliseconds so outside of this while loop we know that the processing has completed so let's go ahead and print out the text result so let's print out transcription completed and then print out transcript dot get text okay that should be it that should be everything we need so let's go ahead and run it and see if it's working okay so there's the post and the response we get from the post and now it's queued and processing processing still processing it's processing it's going through our loop and there we go it finally got completed as the status in the response and printed out the text these pretzels are making me thirsty and so it looks like it got cued and then processed for one two three four five six seconds or so and then completed that's pretty cool right it's pretty neat to be able to in your program submit an audio file and get a text transcript of it and with just a little bit of code and a good api you can do exactly that in your own java program so this is the basic way that you can interact with the assembly ai apis once you get the basics of this working though there are a ton of other features that you can explore as some quick examples it currently supports english spanish french german italian and more and the list of supported languages is growing all the time another cool thing is as a part of the response it actually breaks down each and every single word that is in the text transcript and exactly at what time stamp those words begin and end so that's really useful if you want to create something like subtitles it can do other things like filter out personally identifiable information or profanity if you want it to if you have multiple people talking in your audio file it can automatically identify and label who said which part and that's really just scratching the surface there's so much more that it can do so i encourage you to go ahead and give it a try click the link down in the description create a free account and play around with it and of course you can also take what you learned here about calling rest apis and apply it to any other api that you might find if you enjoyed this video or learned something please let me know by leaving a like and be sure to subscribe so you don't miss each new java tutorial and be sure to check out my full java course in the link down in the description as always thank you so much for watching i really appreciate you being here with me and i'll see you next time
Info
Channel: Coding with John
Views: 252,446
Rating: undefined out of 5
Keywords: java, codingwithjohn, coding with john, java beginner lesson, speech-to-text api, assembly ai, speech recognition, assembly ai api, assembly ai documentation, java rest api tutorial, java rest api project, java rest api call, call REST api from java, java rest api, rest api java, web service call in java, rest call in java
Id: 9oq7Y8n1t00
Channel Id: undefined
Length: 29min 14sec (1754 seconds)
Published: Mon Jun 06 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.