Create a Basic API with Ruby on Rails - Part 1 - Returning JSON Data

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys this video is going to be the beginning of a short series where i build a basic api with rails and the intent here is to kind of be a single place or single app that both hosts the like html pages and also an internal api or external api based on like maybe other apps that want to communicate with your app or you know some mobile device or something like that so commonly on an iphone or something they those usually talk to some other app somewhere or some hosted application as opposed to just being the one place there that where the data lies that's not always the case but it's a common trend of how apis are kind of more of the convention with that world and with rails you can kind of build this monolith app that has both or you can create a whole separate app it's up to you usually constraining it all to one place is is kind of the convention of the rails world anyway so you'll you'll come in here like a building a monolith is more of an approach that might make more sense or just building a ruby on rails backed api that has like something like react or vue.js or something on the front end that takes care of the client side so you'll you'll have these two separate apps that juggle the data back and forth and then kind of just do their thing separately but ruby on rails is commonly the choice for something like that because of active record it just makes creating data a breeze in the sense of the database and the the dsl language or the domain scripting language to create resources on a given app so this guide i want to just essentially walk you through the steps i would take and then some more advanced stuff you can use to format the data that might come back as json as opposed to html and a typical rails app so let's go ahead and get started i'm going to create a new rails app i'm going to use my templates it's called kickoff tailwind you don't have to use this i think it for me it's just more or less just habit at this point it just saves me some time and the scope of adding some gems and configuration to the app so check it out if you haven't and i'm going to use for the subject matter here i think i'm going to use bands and songs and kind of their maybe their album names so maybe we'll have a band that returns it's like an object that returns the band members and maybe their albums so to speak so let's say rail's new let's call it a band api just kind of just the general idea there and we could call we can use api mode in rails or you could basically create one that's solely for both i'm going to roll with both for now because we could have a front end on this i'm not going to go crazy on the javascript side but if you wanted to pass api you could just do that like this and it should be set up to do such a thing maybe it will do that so we'll just roll with the api and see what happens so let's go with that trying to think if i should even deal with a template at that point i don't think i'm going to so let's just do that rails basic vanilla app that's api mode and we'll install that okay so with the api mode that pretty much assumes you're not going to install too much in the assets so that means javascript doesn't exist in this world views don't really exist there is a view that you can mount like a vanilla javascript app too yeah actually we do have some some channels and stuff for websockets but that's just essentially how that's going to work look at add stuff as we go so i'll just ls i'm going to find cd band api and let's just check it out in vs code so in an api based app you're going to have a little bit different construct the main thing to note is the controller layer inherits from action controller api class so it's no longer application controller so that's more of the rails convention initially and then we don't have any of the the basic views like it's all just basic mailers and stuff in here so nothing really to be concerned about from the view level so the representation here is assuming you're going to be using some sort of javascript engine or something on the front end to return stuff back so i'm going to generate a scaffold called band and within it it's going to come back just some basic stuff so we're going to get our routing for our controller or our routing i should say and our model so the if you do a scaffold in api mode no views or assets are added it's going to return json by default so if you see on a typical rails app this will like return a format and this will all just be bailed built in so in the response i believe it's just going to return if you go to a certain url we'll be able to see that json based on i believe a gem that is installed not j builder yeah we basically have almost nothing in this app so that's okay rails will just return json so let's migrate that data okay and i just want to boot up the app and see what happens so it's not going to really do much because we don't have any views but we can go and go to the routing and we have resources bands really don't need a root route so i can just go to directly to localhost bands nothing's going to come back but you'll notice that the response is json format so we're basically just going to return json in our browser it's not going to be anything to view so why don't we create some bands i'll do that rails console and we could say band.create these are literally off the top of my head i'm not i'm pretty much recording this in real time so let's say i don't know c dc there's one and dot create name rolling stones band dot create led zeppelin i think that's how you spell it i should know that and maybe one more [Music] that's another good band the beatles bands i feel like everyone's heard of okay there is four bands let's go with five so one more guns and roses i don't know not really a favorite but i feel like people have heard of it i don't know if the n is capitalized or not whatever okay fans are created cool that should be great we've got data coming back now that's just literally how it's going to work and you could return json different formats there so if you don't want to return and create it at for instance i believe you can modify how that's returned so with our data coming back we now have a essentially just dump of all the data that is in our database around the band and what's nice is that's basically just available by default but if you want to manipulate this data it gets a little tricky and you can come back and just return certain bits of data that you might need for a simple api but a common convention is to use a specification for building apis this is more of a choice that you might take at a team level to return json in a certain format certain pattern an example response might be here of like a blog post with articles returns certain data in a certain fashion so if the article's got pagination you'd see that stuff here the set data on the articles is like the actual title any relationships involved so in that case an author or comments actual links to those and then you can actually include the data itself so included represents the block of actual data on the type of stuff associated with maybe the comments or whatnot and it's kind of neat how it works and a way to extend this and use it in a rails app at least the method i've heard about in the community is active model serializers so it's essentially a serializer pattern that allows you to return json in a certain format as opposed to something that's just stuck in rails we're rendering all of our data at this point we've got everything dumping so everything included in the object is going to be the ide the name created at updated that and that's useful i don't know that we need the timestamps so much and we probably want to modify those if we did so we could return only certain elements in this case so you could say name and it would return the name of the bands only so that's pretty useful so we can also come back and render we need to add another resource if we say rails generate let's see member we'll say and references and we'll say name pretty much the same so like that that'll give us our model let's run railsdb migrate and then in our models we'll have member it's going to say belongs to band band will have many members so we can save that down and essentially it's all nothing can change here but we can go back to that api that's returning i believe we can include members okay so if we create a member now if we'll go rails console and i'll do member dot create let's see who is the first band ac let's just say angus young we need a past name and we'll say band id one because angus young was an acdc which is the first band we created should have id of one let me set that and let's see what comes back in okay so we've got our association set up i'm returning just the bands at this point but i know we do have the members so if we go to members i need to add the routing i think so routes bands members basically that also would be bands one members something like so ban id members member id one i know i just created a member but for now what i want to do is set up active model serializers which is a third-party gem that's going to allow us to contort the json that comes back as opposed to kind of trying to do it built-in stuff with rails and since we are in api mode using jbuilder which is another way to approach rendering json a little out of the question because we don't have the view portion intact so that's i mean it's okay you don't have to worry about it too much but now we need to leverage a gym for that and it's a little involved but it's not too bad so it's going to come with some generators which will create a new active model serializer i can't say that and just kind of go from there so we'll say i'm going to go to rubygems ruby gems active model serializer if i can spell cereal there we go and it's pretty popular gem for just returning formatted json in a way you basically would want and its approach is object oriented so it's a much like how models work already in your database and or in your app so let's add this to our gem file real quick so i'll go just i mean honestly anywhere just throw it here and run bundle okay so it's going to come back with some stuff that it's going to use and the way this can work is running some dependent serializers now if you just run rails you should have a new generator option let's check it out should have it somewhere maybe we don't okay rails generate let's run that first and see what we can generate okay now we've got more serializer so we've got one now so i'm gonna run that and it's gonna just mimic what we've added so rails generate serializer and just go from there and we can add stuff to the app in that way so it's gonna create a new folder in our model or in our app directory called serializer we'll have band serializer and it's going to default to just including the id and i'll include name too so save that down if we go back that's going to just basically inherit from what we're working with on the model so now if we go to our controller i'll just show you by example we're just rendering bands um and band itself so if we go back i believe this should change we need to boot the server up i don't know if it'll change on the index but it will on the show page yeah there we go so now we got the id and the name of returning because we're inheriting that serializer action and since i just added the member class we can do the same cool thing we do in models in the serializers but we need to create the serializer from member first so let's do that a new window here i'll kill this one so rails generate serializer and we'll call it remember we'll just go with that i think you could pass attributes there if you want as well up to you so again id here and name here and what we can do is have band serializer has many members and let's see what that does there we go so now it's returning json in a rich way that's going to essentially have an object a subchild object that's called members and in it since we've created one in the past i created a new record that's angus young associated to this id so let's create a few more members and go from there i don't believe you need to have belongs to here but we can go and do that anyway so you can build in those associations so maybe we'll have on um rails create remember create i know malcolm isn't alive r-a-r-i-p but i'm gonna add him anyway and maybe for the beatles let's add i don't know john lennon also not alive r.i.p what band was he in for i obviously i know he's in beetles but the id i'm thinking of so john lennon there then we could say paul mccartney and ringo starr i think it's two r's could be wrong don't sue me george harrison okay guns and roses i'll just put slash and i think that was five yeah and what we got rolling stones mick jagger is it mick is it two yeah keith richards i'm just adding a few per band obviously it's not everyone i don't want to take up too much time okay i think that might be wrong but yeah we go two and let's say he's up one we'll just have robert plant i think it's three jimmy page john bonham i'm blanking on the bass player right now john paul jones i think i spelled bonham up there wrong too again don't sue me but now if we return that data we should see a lot more people involved which is sweet another cool thing about this gym is the way you can return json there's different approaches and one is called json api so that's kind of a spec so json api and essentially this is just a way a format you can return the json in a certain format that might make sense for team wide stuff so if you can all agree on a format this is just kind of a truth or source of truth so if we return this in a certain way this actually has a configuration that allows you to do such a thing i believe i'm not sure if there's a guide for doing that i know there's a configuration to adding this i don't know where it is though let's just read this there we go bundle here's more about it if we want to use the json api there's an adapter for that we can add it to a config in our initializers directory so why don't i do that just to show you by example if you go and add initializer or maybe we'll call it active model serial doesn't really matter and you can just say this it's essentially pass that in and that'll autoload when you boot up your app so we just need to restart server and go back now if we go back to our app see it comes back as this this format now which is cool you didn't have to do anything so now you've got this the spec essentially in your arsenal if you want to go back and render things a certain way that might make sense to your team that's kind of just a set way that they can expect going forward i don't know if it i love this simply because you have to like go way about down the object train to find the data you're looking for but it's still pretty cool that it's like a spec and just kind of a place that is centralized to your app so i'll probably actually bypass this and remove this file for now i don't think i'll make use of it but that's essentially the beginning stages of setting this up active model serializers or make this a godsend so if you were to do this in rails yourself and you're not on an api based app you would either need to leverage jbuilder which i can cover in another maybe another app which is essentially when you create a jbuilder if you've ever scaffolded anything that comes stock with your new rails resource so if you see a file called jbl j builder at the end that's kind of returning json by default and rails is smart enough to know to do that by itself so this hooks into that flow and just kind of manipulates what you want to return when you want to return it so it's kind of a neat thing so you can even go you know have complex relationships with these which is why i think a lot of people advocate going this route this has many and belongs to pattern just kind of takes care of it all as opposed to you need to type it all out and rendering it in your jbuilder stuff but yeah very powerful i hope this was a decent enough intro introduction to api getting the json returned in the next video i'm going to start building the routing for a basic api so you'll see that coming up so i'll see you in it
Info
Channel: Web-Crunch
Views: 16,535
Rating: undefined out of 5
Keywords: web-crunch, web crunch, web development tutorial, coding tutorials, learn to code, how to code, rest api, rails api, ruby on rails, rails json api, ruby on rails serializer, ruby on rails tutorials, ruby tutorial, rails tutorial, frontend development, backend development, ruby rails 2021, ruby on rails 2021, ruby on rails tutorial 2021, ruby on rails for beginners, rails api tutorial, json api tutorial, active model serializers, rails 5, how to create rails api
Id: 3S9fyfmCf1A
Channel Id: undefined
Length: 20min 17sec (1217 seconds)
Published: Fri Feb 12 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.