Rails API Series: Our First API

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] what's up guys this episode we are going to build their very first API and talk about all the little details that you will need to be concerned with when you're building out your own api's so first off let's start by creating a new application called weather what we'll do is we'll build a little bit of weather service so you might imagine that your iPhone has to hit the server to get the current temperature when it displays that so we'll be building that server for recording and extracting the current temperature for these locations so our application is going to require a couple things I'll have a location model every location will have a name ideally you would also add geolocation to this so that your location can be searched upon so wherever you are currently at on your phone you could search for the closest city or something like that and return the temperature for that but in our case we're going to keep this simple and start with just a name then we also need a model for the actual temperature and status of the location so we'll just have like a recording model with a location references a temperature as an integer and a status which could be sunny rainy cloudy whatever the case so we'll run rate DB migrate and setup our database and we can open this up and maybe go into our seeds to set up some example data so here we might say l equals location dot create name is New York City and l dot Recordings I create temp is maybe 32 degrees and cloudy so then maybe we also add some historical data in here so maybe it was a little warmer before maybe got a little colder to 28 degrees and went really cold to 22 and it was kind of alternating between rainy and cloudy but then it became sunny and 22 degrees out so we can have our data like this obviously you would want to record the actual timestamps for each of these days or temperatures or whatever if this is checked hourly or on a minute basis you can go and also set to created at on this we're just going to create all of these at once and we'll order them by ID rather than created that so that we can see them in order we need to set location Darby - it has many recordings then we can hop into our terminal and read rekha DB is seen to add those to our database and if we load up our rails console we should be able to see a location dot last dot recordings that last and that should give us that temperature of 22 and sunny and it does so that means that our database is all set up so now we need to go into our application and start building out our API the way we're going to do this is by going into our routes and we're gonna add a namespace in here for the API and the reason why we want to use namespace agir is because we can then define our resources routes for locations and underneath them we can also say resources recordings so that you could grab say historical data or whatever and that will separate those out from resources locations down here which might be for the browser to load up the HTML page for it instead so our API can be designed in a separate folder and that will separate out the controllers and the abuse for it in case you're using jbuilder to render the JSON for the AP so this allows us to have those two separate sections of our routes that are specific to the API and we can contain that all in the same rails app which can be nice now the other thing I want to add here is another namespace though for version one so that we can begin versioning our API there are a lot of different ways you can go about versioning stripe has a really interesting one where it records the current version of the API and then saves it to your account so that it automatically remembers that version which is pretty neat more typical simpler approach the reason why you will want to version your API is that you may not control all of the code in one app so when you deploy your rails app your mobile app might be separate and if it hasn't been updated at the exact same second as your rails app then your users will probably see breaking stuff so that might mean that logins don't work or they can't pull the weather or any of that stuff and that would be really bad so you need to do it in versions so that you can say okay this version has this functionality the mobile app can implement that but when we want to change it we roll out a new version and then once that is rolled out then our mobile app can opt into using the new version now this is important for your own kind of separate teams so maybe your mobile app is a separate development team than your rails app you can deploy those independently but this also becomes incredibly valuable when you have other random people building against your API so if you have a public API that anyone can use you don't want to go break their code so you need to version it so that they can choose to upgrade versions and you can communicate to them while we rolled out version 3 so we're turning off version 1 at this date so make sure that you upgrade if you no longer want to support it so versioning is going to be important we'll talk about that more in the future stripe has some really really interesting approaches to that which I want to talk about when we get around to talking about anymore but this is all we really need to do to create our routes so let's go into building our resources now right before we do that let's take a look at rake routes this is going to show us that our URLs are API v1 locations and slash recordings after that if you want to access those and the namespace actually creates folders for our controllers and our views for these in the API so that means that our controllers are going to be a little bit different than normal we're going to need to create a directory inside of app controllers and we'll call it app controllers API and then we'll make a directory called app controllers API v1 and inside of there we can say let's edit app controller's API v1 locations controller dot RB and this will be the file that we will edit so let me open that up and we'll have our API v1 locations controller this will just inherit from application controller as normal and we'll have our show action this would be what you would request for a specific locations temperature so we'll use that we will have before action set location just like you normally would expect in a regular rails controller so we'll have set location this is going to grab it by the ID so we'll have at location equals location dot fine params ID and then really all we need to do is build our view for this so we need to make a directory called app views API and we need to make one inside of that called v1 and one inside of that called locations and here we can say edit app views look API v1 locations showed JSON G builder which is built into rails it gives you the ability to say sign dot whatever attribute name that you want so you can say idea and this can be at location dot ID and JSON dot name at location dot name and then you can have anything you want like a block and this could be the current recording temperature so we might say here temp is at location recordings that last temp and the status would be the status so this is a way for you to kind of define your JSON output visually in a structure which is kind of nice and this structure allows us to actually put our JSON formatting into the views folder which can kind of organize this a little bit nicer for us in some cases now you could also do this and just say a render JSON and create a hash in here and return the exact same format of a hash so say a location dot idea and it's so on where you could replace the format with just a regular old Ruby hash now the nice part about this is that rails knows that we are looking for the JSON type of file format when we request this so we can just define it in our views folder and it will figure out how to render that for us now let's start our rails server and try this out in the browser now the reason why this works nicely in our browser is because we don't actually have any authentication yet so we're not passing in a token we can just load it up in our browser and see it our JSON as we created it so as you can see jbuilder effectively just builds a hash and then it's in JSON format and our browser can then parse that out into an object in JavaScript what's really neat about this is that now that we have this URL we can go into anything we want we could go into Python or swift or Android or Ruby or JavaScript and we can hit that URL and we can grab that data so even if we were in bash and we wanted to run curl we can grab the data in a curl request and then parse that string response as JSON and then our bash code could even have access to that so you can build your own stuff to consume this API now and if it ever changed maybe the format changes so we don't have current anymore or something then you could update the version and that's really the only difference that you would need to change and the other cool thing about this is if you notice this code is nothing special to API is the only thing that we did was we introduced a version but the rest of this code is very very much your standard rails controller code the output of the show action is in JSON jbuilder format which is fairly common if you happen to write JavaScript to make an AJAX request to load up some data dynamically rather than HTML so this is almost exactly what you would normally write and I wanted to point that out because there's a lot of confusion between how do I write regular rails code and I need to do an API and it seems like it's a different thing it's really not a different thing it just has chosen to use a little bit different authentication which we haven't talked about yet it uses versioning and it uses JSON it's really not a whole lot more that's specific to API is they are really pretty much the same as building your normal rails app now with that said there are important details that we do need to take into account to build and easy to work with API for example if we were to remove dot JSON as the format we're gonna get an error unknown format the reason for that is because well we didn't specify the extension in the URL if our API is always going to return JSON or is the default we might as well force our controller to make sure that it uses JSON all the time so one of the ways we can do that is we could build our own API controller so if we go into app can trollers and say API controller dot RB we can say class API controller that inherits from application controller and this could say before action set default format and we can have a method in here called that and it can say a request stop format equals JSON and override whatever is in the URL that way we always have that format and we can say API controller is the class that we inherit from now for all of our API controllers and that way this is kind of acting as the parent and enforcing all these kind of defaults upon all of your API controllers so that is nice because now we can request this without dot JSON and we are going to get the expected result every time the trouble with that is of course if you wanted to support other formats like XML it is not going to work but you can just simply tweak this code to say well if it's XML leave it if it's anything other than XML force it to JSON and that will work so that's it for this episode we are going to be diving into authentication at formatting your JSON and a better format than just kind of arbitrary formats will talk about more versioning error handling and a lot more in the next episode so I will talk to you then [Music]
Info
Channel: GoRails
Views: 19,066
Rating: undefined out of 5
Keywords: Ruby, Ruby on Rails, Rails, Javascript, HTML, CSS, Servers, Databases, APIs
Id: WZ--LRRyeTQ
Channel Id: undefined
Length: 14min 51sec (891 seconds)
Published: Mon Dec 19 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.