Playing
01. Standardised Responses with Laravel Responsables

Episodes

0%
Your progress
  • Total: 15m
  • Played: 0m
  • Remaining: 15m
Join or sign in to track your progress

Transcript

00:00
If you're building an API in Laravel, it's likely that you are outputting responses to show if something has been successful or not. Now what if there was a way to standardize these responses so you didn't have to repeat yourself in every single controller that you create? Well luckily Laravel has a responsible interface which simply put allows you to convert an object into a response.
00:26
Now I've already set up a Laravel project here with a very simple topic store controller. I've gone ahead and created the model and migrated this so we can get started on creating some topics directly from a client and we're going to start off by looking at how we might previously do this then we're going to convert this over to use a responsible object.
00:49
Okay so inside of an endpoint like this that we can just post through to with a title we want to go ahead and create out a topic. So let's go ahead and just do this in the most basic way that we would. So we're going to go ahead and say topic create and of course this is very basic. We'll grab from the request just the title and then we'll just go ahead and return the topic
01:10
just to get that data back into that endpoint output. Let's make sure we put in the namespace for topic. Okay so now that we've done this let's go over and just send a request through with a title just in here. Okay so that's been created if we just head over to the raw response here you can see that we get this output here and we can even view this as JSON so this just gives
01:31
us the topic that has been created in the database. Okay so now that we've done that we probably want to make this a little bit more friendly for the person consuming the API as well as catching any errors that we get when we create a topic and then returning a response to show that. So the first thing that we'll do is just change up the response here and rather than outputting
01:55
the object itself we might want to go ahead and sort of try and standardize this response. So we're going to go ahead and use response JSON in here and we're just going to give a message just to make this a little bit more friendly. So let's say successfully created topic and then we might want to include some data in here as well and that's going to be the actual topic itself.
02:16
So we're just kind of wrapping this and just showing something a little bit more useful. Now what we could also do is we could wrap this in a try and then catch any exceptions that are thrown by catching throwable and let's just pull this in and then we might want to do a very similar thing here and then show some sort of error. So of course we don't want to
02:39
return the data there and we might want to say failed to create topic. Of course this is a really simple example but depending on what you're building the structure of this will be pretty similar. Okay so let's go back over to our client and create another topic out and there we go we've got a much nicer response here. You might want to include other bits of information but you kind of
03:01
get the idea. Now what happens if the topic fails? Well we should see this response here. What we're going to do is head over to the topic model and just simulate this by going ahead and creating a booted method and we're going to say that when this is being created and if we just get this round in the right order first of all that would help. So when this is being created all I'm going
03:26
to do is throw an exception with something went wrong and that should do it. So if we come over here and send this across now we get that output failed to create topic. So we're just going to use this here to simulate something going wrong while the topic is being created. Okay so this is all well and good but if we create another endpoint we're going to have to pretty much replicate the
03:53
entire structure of this. What happens if message needs to change to something else or you need to add some more data here? Well you're going to have to go through every single controller that you have and modify this to standardize each of the responses that you're just outputting here and that's what this video is about. We're going to look at how we can make this into a standard object
04:15
where we just pass data through to the constructor and output it in a very very structured way. So let's start with a successful response and turn this into an object that implements the responsible interface in Laravel. Now I'm going to go over to the topic and just get rid of this so we can actually see this successful message and we're going to get this and refactor it. So let's
04:37
get rid of that and start to create an object which represents a successful API response. So I'm going to put this under HTTP that makes a lot more sense and I'm going to create a folder called responses and of course you can put these anywhere you want. So I'm going to create an API success response class inside of here. So let's go ahead and add the namespace to this that's now
05:03
under HTTP and responses and we're just going to create out a standard class called API success response. That is the first step. Okay so now that we've done this we're then going to go ahead and implement the responsible interface. Now let's just take a look at this. We just need to implement a to response method. All this is going to do is when we return this object or this class
05:31
it's going to convert it into a response for us and it's going to use what we return from to response and we also get the request injected in as well which is really handy. So let's go ahead and create out that to response method in here. To response and that gives us the request in here. Great. So let's just test this out. I'm just going to go ahead and return in here
05:54
response and JSON and we're just going to say success true just to test this out before we add some more data. Okay so how do we use this API success response class now over in this controller? Well we just new it up and return it. It's as simple as that. So return new API success response and that is all we need to do. So let's go over to our client here hit enter and there we go.
06:22
We've returned that object but of course what's happened is Laravel has called to response getting the request in if we need it and it's done everything that we need to in here. The benefit of this now is that we can go ahead and start to pass some data through to here that we want to construct in that standardized response. So if we go over to the API success response here
06:44
create constructor out what are some of the things that we would want to see in here and let's just pull this up because we don't need anything in there. So we would probably want the data so the thing that we want to represent like a topic. So let's go ahead and call that data and we would probably want some sort of metadata as well so a success message something
07:08
like that. So let's go ahead and create out a protected array of metadata that's just additional data about this. We'll leave it at that for now and then we'll add in a few other bits in a moment. Okay so the data is going to be output here and then the metadata is going to be output here and that's pretty much all we need to do for now. So we can just go ahead and pass this in now.
07:35
So we want to pass the topic in as the main data and then maybe we want to pass in a message just for the consumer of this API. So topic created successfully. Let's check out the difference now. So let's go over send this request across and there we go we have a standard API response with the data and the metadata. That means that inside of any other controller that we create
07:58
we can now just return this object and that's going to give us the same response every single time. We need to update anything in here we can just go ahead and do that in one place and that's going to be reflected everywhere. So what are some other things that we could add to this that would be beneficial that we would then take advantage of of not having to update this
08:18
every single place in our app? Well we could even include a response code in here as well because we're using response JSON. We can pass the response code into the second argument of this. So we could accept this in but also include a sensible default. So let's go ahead and create out the code that we want to use here. That's going to be an integer and by default we could
08:42
set that to a 201 for example or just a 200. So let's go ahead and say response and we're going to pull that in from illuminate HTTP and these have things like HTTP accepted, HTTP okay, which kind of makes sense for this example. What we could also do is start to accept in some headers because we might want to send headers through to here and that's of course
09:08
going to be an array of headers. By default we'll leave that just as an empty array. So now what we can do is we can replace this out with the code which by default is 200 and we could also optionally accept in some headers. Remember we've set a default of an empty array there so we don't need to include that and we don't need to include the code. So now if we go over we have our API success
09:31
response which is going to work in exactly the same way but we could also add say a 201 to signify that this has been created. That's going to change the status in our client here and you can see that we get that changed as well. So we don't need to do that every single time we do a response JSON because everything is included in here by default. So we now have a nice class or an object because
09:55
obviously we're newing it up here which gives us the ability to pass all of this information in, standardize the response and return it to the client much easier. Now the slightly more difficult one is the API error response. So we're going to go ahead and create that out in here. I'm just going to copy and paste all of this just to save some time. So API error response and let's paste
10:20
this in. Let's get rid of all of this and let's get rid of all of these as well. Okay so of course we're going to change the name over here to API error response and we should be good to go. So over in our controller now rather than return this within here we can do the same thing. We can return a new API error response and what are some of the things that we might want to pass into here?
10:48
Well it would make sense to pass the actual exception in so we can start to extract some information out of this and of course go ahead and give that to the user. Then what we could do is include some metadata. So we could either do that as an array or we could do that as a single string and just output an error. It really depends on what you want to do. So I'm going to say fail to create
11:12
topic here and then we could go ahead and also pass in a status code in here as well and that of course depends on what went wrong. You could extract that from the exception or you could just leave it out and have a general error. So over in API error response let's first of all accept in the throwable thing exception and then let's go ahead and accept in the message as well and we'll cast
11:38
that here or type in that to a string. So let's go ahead and pull in throwable and let's see what we can do with this inside of here. So let's go ahead and return again a response and use response JSON and really all we want in here at least for public use so anyone that's consuming our API is just going to be the message. We don't want to reveal any information in here about the
12:01
exception really to people consuming our API. So let's try this out and then we'll see how we can take the exception data and show this only when we're in a local environment or an environment only with debugging enabled. Okay so I'm going to go over to the topic and bring this back and let's go over and send this through. Great we've got another standardized response here using that
12:27
responsible class just inside of here. Okay so what happens about this exception information then? If we're on a local environment we'll probably want to include some more information about this. So what we could do is we could pull up the response here, set the message in here and then add additional data to this if we're in an appropriate environment. So let's go ahead and
12:50
just get rid of this, change this over for the response and then in here check if we're in a local environment and then add the details to this. So what we're going to do is we are going to check first of all if we actually have an exception. So did we call that E or exception we called it E. So if we have that exception and if we're in a debug environment so we could
13:15
probably go ahead and hit app and debug and that comes from this value just here app debug over in config and app we have debug which pulls from our env. Okay so if that's the case what we can then do is add to our response. So we could set a debug value in here and we could set that key to an array with a little bit more information. So we could include the full exception message in here
13:47
so this E and get message. We could include the file for example so we're just going to go ahead and say get file. We could include the line which might be helpful for a developer so get line and we could include the trace stack as well if we really wanted to. So get trace as string so we don't actually output a huge amount of data. Okay so let's try this out. We're currently in debug mode
14:14
so what we should see here is the debug information, the message, the actual message of the exception that was thrown, the file, the line and all of the trace inside of here. I don't actually think that's too useful at the moment so I'm going to go ahead and get rid of that just so we're not outputting too much information. There we go. So that gives us a little bit more information but if we're in
14:34
an environment where debug is set to false then of course we're just going to see the standard message just in here. And of course this is very simple. You could add more information here if you wanted to. You could pass more data down to here if you wanted to. For example this could be an array like the metadata that we saw over in the successful response. It's really up to you. The
14:55
whole point now is that wherever we need to return a response we have a stand way to do it. We just new this class up, pass the exception in and pass in the data we need. Same with the API success response as well. To finish up let's just make sure that our API error response also allows us to include in a response code. By default let's go ahead and grab the response and just an internal
15:22
error maybe. So an internal server error and of course we also might want to include some headers in this as well. Exactly like we did in the success response. So it's exactly the same deal. We just want to go ahead and pass in the code here and also the headers. So everything is nice and standard across both the API error response and the success response.
1 episode 15 mins

Overview

Building an API? The Laravel Responsable interface is absolutely essential for keeping your response structure the same across your entire application.

Alex Garrett-Smith
Alex Garrett-Smith
Hey, I'm the founder of Codecourse!

Episode discussion

No comments, yet. Be the first!