Exploring The Wordpress REST API & React Integration

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] this video is sponsored by the ultimate freelancing bundle by study web development comm which gives you everything you need to start your own freelancing business including 130 page in-depth guide invoicing and client proposal templates website templates an SEO checklist and much more visit the link in the description and use the code brad 25 to get 25% off hey what's going on guys so in this video I want to take a look at the WordPress REST API so what's really cool about this is you can use WordPress as a content management system and this is especially good for clients especially if you're freelancing and so on because they can add their own content however you can still use a single page application on the front end with react or view or angular and just connect to the the REST API and you can access all the resources that WordPress offers you can use custom post types which I'll show you how to do using a plug-in as far as authentication there's multiple methods what I'm going to show you is a plug-in called JWT REST API it allows us to use JWT which is JSON web tokens in order to get a token to authenticate to be able to add a post or whatever add content so I'll show you how to do all that through postman which is an HTTP client and as far as react we'll just set up a quick react application on the front end and just kind of interact with it a little bit fetch some data I'm not going to get into authentication in the react app itself because that it'll just take too long off to use Redux and so on but if you watched my Django and react series where we did implement front-end authentication it's pretty much the same thing you just store the token and then when you make a request you send that token along with it in the headers alright so we'll talk more about that in a little bit but this is the documentation for the REST API and just kind of gives you some information shows you the endpoints what the requests and response look like basically you go to whatever your WordPress URL is slash WP jason and that will give you all the available end points and if we go to reference here you'll see all the different resources that this allows us to get and work with so posts categories pages users media all this stuff is available and we can also use custom post types using a plug-in which I'll show you so obviously we need to have a WordPress installation so if you want to use xampp or WAMP or something like that that's fine if you want to use a remote WordPress installation that's fine we're gonna use docker and I actually made a video about two weeks ago creating this docker compose file which will set up MySQL PHP myadmin in WordPress with Apache all in containers in one simple command alright so that's what we're gonna do so if you want to follow along just make sure you have docker installed on your system and then we're gonna grab this and jump into vs code I'm gonna create a new file this is just an empty folder and let's call this docker - compose dot Gamal and I'm gonna paste this in I'll make sure that this is all indented correctly okay so once we have that saved you can just simply run docker - compose up detached and that's going to set up the MySQL database PHP myadmin in WordPress and it's gonna bring all the the files in over here as you can see and you just want to wait a couple seconds for all the files to show up before you go to localhost 8004 our wordpress service it's basically mapping port 80 within the container to a thousand on our system and you can change you could change this if you want alright so let's try it out we'll go to localhost port 8000 and we should be able to now install WordPress okay so site title I'm just gonna call this book reviews I'm going to show you how to add a custom post type of books rather than just using PO so username say Brad simple password and install so we'll go ahead and login and it's as easy as that to get WordPress setup and of course we do have our standard WordPress front-end template and there's different ways to to handle this you could just put a header function and just redirect just read if someone tries to come here just redirect to your front-end application we'll probably do that later so now what I want to do is experiment with the REST API so if I open up postman and I make a get request to HTTP localhost 8080 a role for error now to fix this we just go to settings and then permalinks and we just need to change a setting so I'm gonna go from plain to post name in common settings and then save and now if we go back to postman and make that same request now it works okay so when I first got started with this that kind of that that took me a little bit to figure out so this gives us like the obviously that application name the description all that stuff and it also gives us all the endpoints so basically if we want to use any of the resources we go to slash WP / v2 and then whatever and whatever resource we want like posts so let's do that let's go to WP Jason slash WP / version - slash posts so what this gives us is an array of all of our wordpress posts which by default we only have this one this hello world but it gives us all different fields like the ID the date the slug status type and then we have a title object with a rendered property that has the title content and then excerpt and you can see the HTML is actually included in here now as far as like the author the featured media which would be the featured image it just gives us the ID so within like our react or view application we'd have to make another request to get let's say the author name so we'd have to go to slash users slash and then that ID so let's say slash one and you can see that gives us the author are the users information okay so as far as like adding a post or doing anything like that where you're you're editing data in WordPress then you're gonna have to authenticate so just to give you an example if I go to post and I go to v2 slash posts and let's try to add a post so in our headers we need to add a content type and we're gonna set that to application slash Jason and then in the body will go to raw and we'll just add our Jason so let's say we want to add title and it'll say post one and then content say this is post one and then status because if we don't put a status here it'll be draft by default we want it to be published so let's say publish okay now if I try to send this what we get is a 401 which is an unauthorized so this means it says sorry you are not allowed to create posts as this user basically we don't have a user now like I said there's different ways to authenticate if you're using the REST API would suggest using JSON web tokens so basically you just need to log in through an endpoint and then take the token that's that's given to you and add that to the headers now this this isn't functionality by default so we just have to add in a plug-in so I'm going to go to plugins add new and we're going to search for JWT and this right here GWT authentication for WordPress REST API we want to stall that and click activate ok and then I'm just going to open the documentation here this view details I'm just going to open that in a new tab because there is a little bit of configuration we do have to add a couple lines to our htaccess file so I'm going to grab the second two because we already have the rewrite engine on so I'm going to copy that and then go into the htaccess file for WordPress and I'm going to put this right here and let's see let's go back and grab this line and put that in as well ok so we want those three lines in our htaccess i'm going to save that close it up now we want to go into our WP config file and i'm gonna go down here and we need to put our secret key and we need to enable cores so let's go back to that page right there and we'll grab the secret key ok so we just want to define and you could use anything here I'll just say secret and then four cores go ahead and grab this define and put that right under it alright so let's save that now we should be all set to hit the endpoint to get a token which as you can see right here it's gonna be WP Jason JWT auth version 1 token and a post request so I'm going to grab that and let's go back to postman I'm going to open up a new tab here make a post request to http local host ports 8000 and then paste that in slash now for this we need to send along content type of application slash Jason and then in the body we want to log in ok so this could be any WordPress login so let's put a username which mine is Brad and password 1 2 3 4 5 6 let's see what happens if it's wrong okay so if it's wrong it just says incorrect password let's change it to be correct and send and now we get a token back ok as well as the email and display name so now we need to just take this token so we'll copy that and we need to go to where we tried to create a post earlier and just add a header value of authorization and in order it's for this to work we need to put in the word bearer because it's a bearer token so bear our space and then paste in the token ok once we do that we send now it added a post ok if we want to add another one let's do post to to send that now if we go back to our WordPress content management system here if we go to posts you can see we now have post 1 opposed to alright so I mean if you guys have have used JWT with with react or view or angular before it's it's gonna work the same way ok and like I said I'm not gonna implement that because it just it takes too long to set up if you watched my react and Django series that I did until they just did it's pretty much you implement the front-end pretty much the same way we used Redux we store the token and local storage we had an auth reducer with a value of is authenticated and we just checked to see if that token was authenticated ok so that's pretty much the workflow you want now what if we want custom types like we don't want post let's say we want books ok so there's multiple plug-ins for WordPress obviously I'm gonna install one say new and I'm going to search for custom post types UI okay so this right here our custom post type UI let's install that okay so that's installed we'll activate it and let's go to over here now you have this add edit post types so I'm gonna create one called books as you can see I've already done this plural it's gonna be books singular is booked and then down here or it says show an REST API make sure that's true and then for the slug we're gonna say books and then down here I'm gonna say we want to we also want the excerpt to be available as well as the author alright so we can do that we'll say add post type good so now right here you can see there's a menu item for books and if I click add new let's say book one for the content I'm just gonna grab some dummy text at lips I'm calm and we'll just grab a couple paragraphs here paste that in we'll grab like the first line here for a sentence and put that as an excerpt over here we'll set a featured image so I actually have some some just dummy mock-ups here we'll use that alright so we'll go ahead and publish and publish okay and let's create one more so I'll add another book say book - let me just grab we'll grab the second two paragraphs and then we want an excerpt featured image you can grab any image you want alright so published so now we have two books now if we go to postman we should be able to say slash books actually no we don't want to make a post request let's just go to a new tab so slash slash host 8000 slash WP - Jason slash WP / version - slash books and now we can fetch our books and another thing there are parameters we can add like let's say we wanted to limit it to a certain amount per page we could add per underscore page and let's set that to 1 so now if I send that it'll just get the 1 so it's an array of Y now if I wanted just a certain book like this one has an ID of nine I could say books / nine and that will give me that single object all right now what if we want to add a custom field like like something else besides this stuff like maybe publisher or something like that so in order to do that we could install a couple extra plugins so if we go to plugins add new we want to search for advanced custom fields and it is this one right here this first one so we'll install that okay well activate it now by default we can't we'll be able to add custom fields we're going to set that up in a second however they're not going to be visible to the rest API so to do that we need one more plugin and that's called ACF - REST API okay so advanced custom fields - REST API whoops what am i doing we need to go to add new and search for that ACF - rest api it's going to be this one right here alright we'll activate it okay so now let's go over to custom fields and let's say add new and this is gonna be the group so I'll just call this books and let's make sure this only pertains to books and then we'll add a field so let's just say publisher okay it'll add the field name here automatically the type is text although you have a bunch of different types you can use here and I'm just gonna leave the rest as default okay so that should be good let's say publish okay now if we go back to books and let's go to book one and down at the bottom you'll see we have publisher so let's say I don't know ABC publishing and we'll go ahead and update that and let's go to book two and we'll say one two three publishing update now let's go back to postman and see if that shows up so we're gonna make a request to book slash nine which is book two so we'll send that again and now we should have published available publisher sorry so right here and you can see it's actually in this object called ACF okay so advanced custom fields so in your application you would just simply you would query the this object okay and then any field inside there that you wanted and of course there's other plugins there's other ways to do it but I think this is a pretty simple way so I think now I just want to jump into react and just kind of mess with this a little bit this API like I said I think I said this is this isn't gonna be like some fantastic application or anything it's just to kind of get you guys familiar with it maybe give you some ideas get the gear spinning spinning in your head so you can start to create some stuff using this if you're interested so let's jump into vs code and I'll clear this up and I'm going to use create react app to create our react application but I'm gonna use npx instead of installing it globally with NPM so we'll just do NP X create - react - app and let's put this in a folder called front-end so that will just generate a boilerplate project and put it in a folder called front-end and you can structure your application however you want and I'm choosing to use react but of course you could use view or angular or whatever you'd like okay so now let's CD into front-end and I'm just going to install two things I want to install Axios to make our requests if you want to use the fetch API that's fine as well and then also react route our Dom because I'd like to have a list of our book reviews and then be able to click a button and go to that single review page or that book page and it's going to be very simple I'm not going to use any styling or anything like that the goal isn't to build an awesome application it's just to give you an idea of how to work with the API alright so that's all set now I'm going to just run the create react app server so NPM start make sure you're in your front-end folder and that will open it up on port 3000 close these other tabs here all right so now we just have our landing page and I'm actually gonna make this smaller so that we have both on the same screen here all right so let's do our I'm just going to do my standard cleanup for create react apps so in the source folder I'm going to delete the app test file index CSS logo and the serviceworker so we'll delete all of those and let's go into index j s get rid of the import for the c index CSS get rid of the serviceworker import and the register method down here save that go to app j s get rid of the logo and just have a div the render should just be a div and we'll just put an h1 in here and we'll just say app alright and then let's go into app CSS and let's clear all that stuff out as well okay I'm not gonna have any styling whatsoever all right so let's go ahead and create a components folder and components and inside here let's create a file called books a s ok so this is going to be the books component this is where I want to make the initial the initial request to our API now I'm going to add inside our package JSON file which is right here I'm going to add a proxy for localhost 8080 and let's set that to HTTP localhost port 8000 okay so we'll save that that way we don't have to include that in our request so inside books I'm going to generate a class-based component and I'm using an extension 4 vs code called right here it's es 7 react Redux graph QL snippets so using that extension I can just do RCE and hit enter our tab and it'll give me a class alright now as far as the state I'm gonna put in books which will be an array and then let's do and is loaded and we'll set that to false so the idea is this is false until we make our request and get our books and then it'll be true we'll set it to true ok let's let's bring in Axios and inside our class let's create component did mount which is a lifecycle method and this is where we want to make our initial request so let's say Axios it's gonna be a get request this will give us a promise and then we'll handle an error with catch ok so the URL that we want to make the request to is going to be slash WP - Jason AP WP and since we added the proxy we don't have to put localhost 8080 P slash version to slash and we're getting books ok but of course you could create whatever resource you want you could you could deal with the standard wordpress post pages users anything at all that is available with the rest api so for the catch let's just do a console log I'm not gonna do anything special here I'll just log the error and then inside then we're gonna get the response and then let's set the state so this dot set state put in our state object and the books we're gonna set to the data that comes back and then let's set the is loaded to true okay so that should make the request now just to make sure let's actually go in our render and let's console log this dot state and we'll save that we'll go to app J s we'll bring in our component so import books from dot slash components slash books and let's replace this h1 with books okay so save that okay this should be uppercase okay so if I open up my console here oh you know what when when we create a proxy in the package Jason you have to restart your server that's why it's saying it's a 404 so let's just go ahead and restart that all right and as soon as it does that it should work there we go so now you can see that we're getting our books now first we get an empty array because it hasn't been fetched yet so notice right here it says is loaded false and then the second one you can see that we actually get the data and is loaded is now true so inside of our books component let's let's get rid of this we don't need that and let's pull some stuff from the state so we'll use destructuring and we'll pull out books and is loaded I'll pull those values out from this dot state okay and then we're going to check to see if loaded so if is loaded then let's move this return up so what do we want to return here we want to basically loop through the books we want to create a list so we're gonna take the or let's return a div and let's take the books and let's map through those so books map and for each one we'll call it book and for each one let's just return for right now just in h4 and we'll put in the book now remember it has a title but that title is an object that has a rendered property we saw that within postman and then let's see down here under this if loaded let's just return an h3 and we'll just say loading and you could put a spinner if you want it to look fancy but again the stuff I don't care about the styling for this at all so let's save that and as you can see for a second it's loading until it gets the data and then it's showing us book 1 and book 2 which are the title and we're getting this this warning just because you don't have a key on this list but what I want to do is instead of an h4 I want this to be a whole new component called book item so let's actually create a new file in components called book item Jas and before we add anything here I'm gonna bring it into books so we'll go right here in imports book item from dot slash book item instead of loading an h4 we're gonna load book item and we're gonna pass in C we're not gonna do this we're gonna pass in as a prop book and we're gonna set that to book actually I don't know why I just did that we want that okay and then it's going to complain about a key like it is here so we need a unique key passed in so let's set the key to the ID the book ID alright so we'll go ahead and save that or of course we're gonna get an error because there's nothing in book item so I'm going to generate a class-based component here and let's go down to the div and we're gonna load let's see let's return a div with an h2 and let's put the title in here and I'm gonna pull the title out of the props so it's two Const it's pull title and remember that's from this dot props dot book cuz that's what we passed in we passed in book and title is still an object with a rendered so we just need to put in here title dot rendered absolute can't spell so let's save that all right so now each each title is showing from this book item component now we do have access to the excerpt so let's put that underneath and I just want to show you something if I do like let's say a div and I put in here let's pull out excerpt and let's say I do excerpt dot rendered and if I save that it shows the excerpt but it also shows the HTML that's there and obviously that's not what we want so we need to use an attribute called dangerously set inner HTML which will allow us to actually parse this HTML so instead of putting this directly in the div I'm going to add to the div and attribute of dangerous dangerously set inner HTML set that to a set of double curly braces we want double underscore HTML and then we put in the excerpt excerpt rendered okay so if we save that now you see that the paragraph tags are gone all right now I'd like to also have the image as well as the author and remember those don't it doesn't just give us the the image URL it gives us an ID same thing with the author so we have to actually make a couple other requests too to get the the featured image and the author so in that case let's go ahead and bring in Axios so I'm going to bring that in from Axios also we passed in book as a prop so we should probably add in our prop types okay so within the class let's do static prop types set that to an object and we have a prop of book and that is going to be an object there is an object and let's say is required okay now we want to make our request in component did mount now I want I want to make two requests one is gonna be to get the image so it's gonna be our WordPress API slash media slash and then the featured media in fact just to make this a little more clear let's take a look at what a book look looks like so this is fetching a single book and we have let's see where is it yeah right here author one and then featured media is ten so it's just giving us the IDs so we can fetch for instance the media by making a get request to slash media slash ten if I do that it gives us a whole bunch of stuff that has to do with the image so it gives us this gives us different sizes so media details so under sizes I want to get the full size and then the source URL so quite a bit of digging to get to what we want but but we can do it so the way I'm going to do it since we have two requests is I'm going to use promise dot all because Axios returns a promise and I'm not going to do nested bends I want to do this in a more I guess readable syntax so let's do const get image URL set that to the Axios request which is going to be a get request and then in here I'm going to put in back ticks because I want to put a variable in and its gonna be slash WP - Jason slash WP / v2 slash media and then we want the ID now the ID we're gonna pull let's pull that from the props so it's a Const and it's called featured media so featured underscore media and we're also gonna want the author and let's pull that from this dot props dot book okay and then we'll pass that in as a variable so featured media like that so that's our first request now the second one I'm going to put which is to get the author so let's do equals Axio stock get and we want to pass in / WP - jason and it's gonna be WP / version 2 / and now we want users okay and that these should actually be back tix so let's change those because we want to put a variable in here alright so users slash and then the author so let's put in author okay now we have both of our requests and we can use promise dot all okay so oops so instead about adding separate thenns on these requests we're just putting it in this promise dot all we're gonna add an array of the with these variables so get image URL and get author okay and then this will give us a promise so we'll say dot then and this will have the data for both inside of an array so let's say for the results we're gonna then set state so this dot set state and let's set the image actually I didn't even add the state yet so let's go up here and let's say we want in our state image URL we also want the author and then let's also do an is loaded as false okay and then once we get this stuff here we're going to set the image URL and this is going to give us this result is gonna be basically an array and the first actually I can just let me just show you what this gives us just for those of you that haven't used promised at all so let's do a console log of result all right so as you can see we get let's open this up we get an array with two objects the first one if we look in data is going to give us the image okay so it has media details sizes full and then source URL so basically that's what we want to target and then the second one is the author so if we look in data we want what do we want here just the name all right so that's what we're targeting so let's go back here I'm actually gonna make this a little smaller and let's uncomment this okay so image URL we're gonna set to res and we want the first object here and we want from data media details and then let's go into sizes and then fall and then we want the source underscore URL okay that'll give us the image URL next for the author we want res one and then we want from the data we want the name we're gonna put that in author and then we also want to just set is loaded to true okay so now down here in the render let's let's see we get the title the excerpt lets get from the state let's pull out the author the image URL and the is loaded so that's from this dot state and then we want to check for it to see if it's loaded as if it's been fetched so if is loaded then in that case let's bring this return up into the if and then after this if statement I'm just going to simply return no all right and now inside here now we have access to the image URL and the author so under the h2 I'm just going to put in a small tag and just say review by and let's put in some strong tags and we should now have access to the author ok and then actually for this h2 though I'm just gonna add I'm just gonna take the margin away just because it pushes it down too far so we'll say style margin bottom zero all right and then we also want the image so I'm going to go right under the small tag with the author and put in an image ok then for the source let's put in the image URL for the alts I'll put in I'll put in the title dot rendered okay and I'm just gonna add here a style I just want the width oops I want the width to be a hundred percent just so it doesn't go out of its container so set width to 100% all right so that should give us the image let's save it all right so let's see it's giving us the author however the image doesn't seem to be working image URLs assigned oh this is in quotes shouldn't be in quotes save that there we go so now we have the image alright and we have access to pretty much any of that data that that comes from the API if you want to add more here now I want to have a link that goes to that goes to a single book page so we'll have to create a route but let's just add the link so up here let's bring in from reactor outer dom we'll bring in link and let's go let's see let's put under the excerpt let's do let's put the link there so we'll say link - and this - is gonna be dynamics so I'm gonna put in some curly braces and some back ticks and we're gonna say slash book slash and then we want the ID which I'm actually gonna pull from this dot props dot book so we'll put in here the ID all right and then we'll just say book review or read review and then I'm just going to put an HR underneath just to separate them out a little so we're gonna get an error because we're using link however we haven't implemented the router yet so let's go to app J s and let's bring in let's say import browser router as router and we also want to bring in route from the reactor outer dom and then we're just gonna surround C down here let's surround this with router and we actually don't need a div here I'm gonna bring in fragment from react and let's just change this right here to fragment fragment which is just like a ghost element it doesn't actually show up in the dom and then we don't want to just place in books we want to put in a route with an exact path to slash and then the component we want to load is gonna be books okay and then let's create another route this is gonna go to a component called book page which will create in a minute and it's gonna go to slash book slash colon ID okay so let's bring that in even though I haven't created it yet so book page book page okay so we'll save that obviously we're still gonna get an error so let's go in components and create a file called book page Jas all right and let's create a class and this is gonna we're gonna make a request to get a single book based on the parameter that's passed in well why is that HR there let's go back to I forgot the angle bracket alright and now if you see these read reviews it goes to book slash nine and if I go to this one hover over you'll see it goes to book slash seven so it gives us the correct ID so in book page let's create a state and book is gonna be an object and let's do is loaded set to false all right and then let's see inside of component did mount let's make our Axios call we have to bring Axio sin so we'll import Axios okay and then let's make a get request I'm gonna put some backticks in here and we're gonna go slash WP - Jason slash WP / version - slash books and then we want the ID now since the ideas in a in a route parameter we can access this through the props it's this dot props dot match dot for Anne's and the / am one is the ID okay so that will give us the ID and then we get our promise back okay so when we get this result we're gonna set state so for our state we're gonna set book to the res data and set is loaded to true okay and then down here in our render let's first pull out from the state book and is loaded okay and then we're gonna check for is loaded okay and let's just move this whole return right here go ahead and move that up here and then after the if I'm just gonna return an h3 and say loading now in here we don't actually need a div so let's bring in a fragment from react okay we'll change these two fragments and inside the fragment I'm gonna have a link to go back so we also need to bring in link from react routered um and let's put link to this is just gonna go to slash and we'll just say go back alright and then we'll just put an HR so let's I mean it's very ugly looking but that's fine so HR then let's put an h1 and I'm just gonna give this actually we'll just do an h1 and this is gonna be the title so remember we took the book from the state okay we set the state when we made the request and that has a title property which is an object that has rendered okay so that's our h1 and then we want to set the content so book content dot rendered however it has HTML in it so we're gonna do our div with the dangerously set in or HTML double underscore HTML and we'll set book dots content dot rendered in fact let's do this let's pulled from this dot state dot book no we'll just leave it like that that's fine and then I also want the publisher okay so the publisher remember was a custom field that we added so under this div right above the fragment let's put in h4 and let's say publisher and remember and all those custom fields are in an ACF object so book dot ACF dot publisher and we could add as many custom fields as we want so I think that should do it let's save that and let's go over here let's say read review and there we go so we get our title we get our content here and then at the bottom we have our publisher awesome so I mean you know this is just a simple example of how to use the API obviously you could make this much more in-depth and you could add authentication I just didn't want to make this a two-hour video and I didn't want to make a series but I think that you do have the tools to be able to do that all you have to do really is is use some kind of state management hold your authentication in that state with the token store the token and local storage so that when you go to add a post or add a book I should say well anything at all that you're adding or updating or deleting you need to send along that token ok so create a login page login get the token store it and then use that to make requests to protected routes and again if you watch my react Jango series or at least just the front-end authentication part of it that'll pretty much show you how to do it if you took my myrn stat course that'll show you how to do it and then there's you know countless tutorials and articles on the internet to show you how to do that whether it's react view angular or something else alright so hopefully this this helped you guys understand a little bit how the REST API works gives you some insight on some of the plugins that can be used but that's it so thanks for watching if you like this please leave a like please follow me on social media and thanks for watching hey guys one of the best if not the best resource I can refer you to for starting a freelance business is at study web development comm slash freelancing the Creator Kyle shared it with me and I can personally vouch that this bundle is well worth it you get 130 page guide to freelancing and it comes with things like invoice templates client proposals HTML and CSS templates a portfolio website access to a private Facebook community and much more so use the code Brad 25 to get 25% off today
Info
Channel: Traversy Media
Views: 151,133
Rating: undefined out of 5
Keywords: wordpress rest api, headless wordpress, wordpress react, wordpress rest, react wordpress
Id: fFNXWinbgro
Channel Id: undefined
Length: 51min 31sec (3091 seconds)
Published: Sun Feb 10 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.