Consume a REST API in Go | Convert JSON to a Struct

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's going on welcome back to nerd academy i'm your host james and in my last video we made a rest api using golang in this video we're going to consume a rest api using goling so let's go there's a lot of free rest apis out there on the web that you can use and test out even using your own projects basic idea is to take the json data from a rest api and convert it into a usable data type in golang in our case that'll be a struct there are two main ways using the standard library both are in the json package one is in marshall and one is decode the unmarshall method is for strings and the decode is for streams that just rhymed we will be streaming the data from the api so we will be using the decode method all right over in our trusty code editor we got our normal package main and funk main what we need to start with is a http client let us create a variable called client make it a pointer to the http client let's import that so now we've declared it let's initialize what we need to do is create a timeout for it to get the dereference that pointer and we're going to create a timeout times time dot second so what this does for our http client to make sure it doesn't get hung and sit there and wait forever we're going to time it out after 10 seconds so we're going to take the time time package and we're going to multiply 10 by 2nd let's create a reusable method because we're going to do this with a very simple rest api and then we're gonna get a little bit more complicated so let's create a font called get json we're gonna pass the url as a string and then we're gonna pass an empty interface and let's return an error so this empty interface will allow us to pass in a struct object or basically anything that is could be an interface which is just about anything so we're going to use our client and get the url so we're going to pass that url in this returns a response object and an error so let's grab those our response error and let's check if the air is not new we'll return that error otherwise we're going to defer closing our response till later until after we're done with it so we're going to use the json package we're going to create a new decoder and it's asking for an input output reader and the response.body happens to be an input output reader or input output read closer but those types match just fine and then we're going to decode and we're going to pass our target in there so this returns an error so let's just return that so if this json new decoder can't decode our struct object then it will return the error otherwise it will return nil therefore when we check this later in our other methods if air is not nil then we're good to go so the first one we're going to do is a silly one called cat facts ninja so that url is catfact.ninja the best thing to do when you're trying to uh get json and convert it into your uh structs you should probably look at the data and see what you need because the cat fact the json looks something like fact and then a string about the facts and then it also has a length which is just how many characters the fact string is let's create that cat fact type struct and then our field we're gonna use we're gonna call it effect be a string and the length will be an int so go will only encode or decode or unmarshall and marshall fields that are exported so a field that exported is uppercase or capitalized so if we did fact lowercase it's not actually exported so we need the uppercase and you've may seen in other structs or fields json like this so this is really useful if you're going to encode your struct and turn it into json and send it up to an api where it's expecting this field of fact for instance in lower case if we take this the way it is now create a struct object and encode it will be uppercase fact and then whatever we put in there and then when you try to set up the api it's not going to find it because it is looking most likely looking for the lower case fact so let's make a function to get a cat fact and the url at that endpoint that api rest api serving up is https catfact.ninja slash fact so at this url if you perform a get request on it it will return a json with a random cat fact so let's declare a cat fact object we're going to use our method we created get json pass our url in and our cat fact in check if air is not new and let's just print out what that error is we're getting cat fact and otherwise let's just print it out a super interesting cat fact catfact.fact all right so in our main we need to go ahead and call that method and let's test it out go run main.go we don't have the address so we can't update this cat factor with anything so when we get to the json it can't dick can't take it and put it in our object here so let's try that again a cat's smell is their strongest sense and they rely on this leading sense to identify people and objects a feline sense of smell is 14 times better than a human probably true so as i mentioned that's um the marshalling and the field names let's take it as it is without the json fields i will show you what i mean so another cat fact actually let's just create it in line random cat fact length how many characters is that we can cheat here 17 all right so now using the marshall instead of the decoder encoder we can create a json object called json string and we're going to get an error from this if something goes wrong so json marshall we're going to take our cat fact to put it in there so air not nil we have an air marshaling else let's print that out and we're going to turn that into a string because it's a byte this returns a byte slice and so this json string wouldn't be that readable so we're going to go ahead and turn it into a string let's try running this again there you go so you can see the capital facts and the capital length so if you were to take this json try to send it up apa may not accept it to fix that you put json fact here backtick json length and if we run it again there you go we got a lowercase fact and lowercase length so the next one is a random user which you might actually be able to use in a project that if you're kind of testing out trying to get just user information that's just random and it's nobody got pictures and stuff like that and emails and names and there's a whole bunch of stuff you can get from it looking at the website and looking at their documentation we can see all the fields there are we're just gonna take a few few items from there all we need is like a name and the email and a picture so let's start by creating a random user and the results was a slice or an array in javascript of what let's call it user result so let's make that type that had a name we're gonna say user name and email type string and then type picture we'll call that user picture let's create the username and let's create the user picture so when you're uh consuming a json and trying to convert it into structs and there's embedded types you have to create each of those embedded types that way it can be unmarshaled and decoded correctly into all the correct objects so we hit a title first string and a last that's a string in the picture there's three there was a large large one a medium one and a thumbnail which could be useful so now we're just going to use this random user struct and it's going to it's a slice of the user results and in the use of results there's the username which has the title first and last name and a picture user picture which has a large medium and thumbnail so i specifically chose these words result name email picture to match what's in the json we can go in here and go json name this will either way this will go into the struct correctly so let's get a random user do the same thing we did before we're going to create a url that url is https random user dot me slash api and that will get if you use a get request here we'll get a random user now if we look at the documentation again you'll see there's a whole bunch of other fields so in the documentation it says we can do question mark include and then all we want is the name email and picture so that way there's not a whole bunch of extra json it's got to parse it's just got to do that we could only we could get everything and it will still only go into these fields here so either way works uh depends on your bandwidth and how much you want so i think it's probably best to go ahead and leave that in there so you don't have a whole bunch of data you're not looking for but either way it will work let's declare our random user object and we're going to get the json again using our url this time we'll pass the address to our user so it can update correctly air is not nil print out the error we get else let's print out our random user's info we're going to have a title a first name a last name say their email that's a string and let's print out their thumbnail picture so we get our user that results and we're only getting one so the first have the slice and we're going to get name title use the results the first and the slice scroll this up so we can see what we're doing here name first user results first in the slice last you get the idea email and user results picture thumbnail all right so let's go ahead and just comment this out here and let's get random user and test that out there we go we got miss yeah let's try another one i'm not gonna try to pronounce that mr rosario yeah see it's very random and we got our uh thumbnail if we go to there we could probably see what that picture is there you go it's a thumbnail so as i mentioned before if we could have just used the base api and it would only fill out the json fields that we created instructs so let's just try it with just the base api there you go so it received all the json but it only parsed the fields that we had set and we have exported in our structs all right that wasn't so bad and that was it and all this code will be available in the link in the description below and if you made it this far i personally want to thank you it means a lot and if you want to see more content like this be sure to subscribe and hit the like button for me to help out the algorithm and if you have any issues or you have any comments or concerns or even questions be sure to leave uh leave that in the comments down below remember always keep learning and if you want to watch more about guesling just watch the video right here and see you in the next [Music] you
Info
Channel: NerdCademy
Views: 269
Rating: undefined out of 5
Keywords: software development, software development tutorial, programming tutorial, software development process, go tutorial, golang tutorial, convert json to struct in golang, convert json to struct in go, decode json to struct golang, consume rest api in go, consume rest api in golang, parse json golang, parse json go, programming, software developer, go programming tutorial, go json decode vs unmarshal, go json decode, go json tutorial, go rest api
Id: aYk8XAKxhxU
Channel Id: undefined
Length: 11min 23sec (683 seconds)
Published: Thu Nov 18 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.