Check out a free preview of the full PHP Basics course
The "Formatting & Returning JSON Data" Lesson is part of the full, PHP Basics course featured in this preview video. Here's what you'd learn in this lesson:
Maximiliano completes the API endpoint example and demonstrates how to format and return JSON data. Headers for setting the Content-type and some CORS configuration are added. This lesson also provide some tips for avoiding sending any content prior to the headers being sent.
Transcript from the "Formatting & Returning JSON Data" Lesson
[00:00:00]
>> Maximiliano Firtman: So, is it ready? Not yet. But maybe you'll say, hey, Max, but it looks pretty good. Yeah, but let me show you something. If I go to the homepage, I'm going to write some JavaScript code now.
>> Maximiliano Firtman: How many of you are comfortable with JavaScript? Okay, so if I do a fetch from here, what I'm doing?
[00:00:25]
Yeah, so I will try to get any wait for the results of that fetch. Then, and I will try to see if I can convert that into JSON, just in one line, you can do that pretty simple like this. So, I'm going to the network down in with JavaScript downloading that URL and then trying to convert that into JSON.
[00:00:51]
If I try to do that, so I try to convert my API, it says, expected property name or blah, blah in JSON at position one boop what? Let me, instead of executing JSON, executing text, so I can see the text, mean the text is there, okay, it seems pretty good.
[00:01:13]
Well, maybe I'm using single quotes. Is that JSON compatible? What do you think? Look here, double quotes. So maybe that's a problem. Okay, let's see. Where is that here? Can I use double quotes? No, well, maybe I use single quotes on the outside and double quotes in the inside, like in JavaScript.
[00:01:34]
What do you think? Yeah, sure. You bet.
>> Speaker 2: No.
>> Maximiliano Firtman: No, why not? It won't let you interpolate. It won't interpolate. So if I'm using single quotes on the outside, in the whole string, then this interpolation is not gonna work. Well, I can, escapism. Yeah, I can do that, but yeah.
[00:01:59]
No, but yeah, we can escape. So then let's go back to, that will quote, and let's try to escape that. And we escape that with backslash. So okay, or if not, I can use the other version of the string. Remember that one that was the triple, triple less code.
[00:02:19]
And then, I mean, that's another option. And then I don't need to escape.
>> Speaker 2: Double quote.
>> Maximiliano Firtman: Double quote, yeah, thank you. Okay, so actually these two characters is one double quote and these two characters are another double quote. So let's see, let's refresh. So let's refresh I'm getting the double quote here, which is fine.
[00:02:42]
Let's try back here, I'm getting double quote. So let's try the JSON version and yeah, it's working. That means that I can get the value and put it somewhere else. Is it perfect my API? Not really. I think there one is step that is mandatory. I mean, it works here because yeah, it works.
[00:03:04]
But by default php servers, typically when it's a .php, they think that you are exporting HTML. So the content type that we are sending to the browser might not be the right one. So when you go here to the network, here I can see my requests and my responses.
[00:03:31]
So you said that the content type says HTML, so the API says HTML, which yeah, is not the HTML. I mean, we are forcing that into JSON and it works. But a lot of apps will say no, this is wrong. The content type doesn't match JSON, it doesnt make sense.
[00:03:51]
And why is that? Because every PHP field by default is exporting HTML unless you change that. Does it make sense? So for that, what you need to do if you call? So we're going to export a JSON to the client. We're going to change a header. And for that, we use a header and you pass a string, the string will look like this, content -type:, you're writing the HTTP header manually.
[00:04:27]
Application/json. That's the MIME type of JSON. So again, it will work anyway, but the difference is that if I try again and I'm going to the network, now we should see in their response headers, application/json, which is the right one?
>> Maximiliano Firtman: Okay, makes sense? And I said that there are two missing pieces.
[00:04:55]
The other missing piece is not really a missed piece, but it's course, not sure how many of you are aware of cost issues. I mean, if you want, it depends on the case, if you're creating an API and you want others to consume your APIs, you need to say so.
[00:05:10]
Because if not, if you try, for example from this website, frontendmasters.com, I'm going to the console and you try to bring this and get the error. Because, yeah, it's not the same nourishing, localhostt and frontend masters to different websites, okay? So to solve that, you can add some more headers.
[00:05:33]
This has nothing to do with PHP, has to do with HTTP, okay? So we have to add the course headers. I mean, you can just Google for that. It's actually one that is pretty simple. So here it's explained all the course problem, blah, blah, blah. It's giving you an example of why this is not working.
[00:05:54]
Give me the header. It's this one. So I just need to also add another header that is Access-Control-Allow-Origin, and I can put one origin such as frontendmasters.com or just star, which means anyone, I don't care. If anyone is requesting for this data, go ahead, give the data, I don't care.
[00:06:16]
So the browser will allow the access to this API anywhere, but just check if your API needs scores or not. Sometimes for security reason is not really 100% secure because through a proxy you can bypass that. But anyway, you can allow or not this course. This is how you create an API.
[00:06:37]
Let me remove the if so we can see that it's pretty simple. So now we have created an endpoint called API dot PHP, that's an endpoint, but instead of creating HTML, it's creating JSON. It's responding with JSON. Also you can change in the header. You can respond with a jpeg, of course if I try this, the browser will expect a jpeg and will give me a broken image.
[00:07:08]
Because yeah, I'm not sending the bytes of an image, but you can see that, but just changing that, php can actually return any type of file.
>> Maximiliano Firtman: Does it make sense? Yeah, one more thing before moving to the next chapter. And is be very careful with the header.
[00:07:35]
So when you call header, you should call the header before anything else. Let me try this. If I run this, well, it works but I cannot see the header. Actually, if you have already sent some strings to the client, you cannot send a header. Actually, PHP works in two ways.
[00:08:02]
I don't wanna get too advanced here today. It can be buffered or unbuffered. But actually, when you're sending bytes or characters to the client, the body of the response has already started, and the head is here, so head body. So you cannot send the header after you send body.
[00:08:26]
So that's why the header should be at the top of your output. And that also means, be very careful with this. What is this? Two lines that I have here, two new lines, because if you don't start your file with a php opening tag, you are sending characters to the output.
[00:08:47]
New lines or spaces. So if you have already sent those spaces, you cannot change the header. Does it make sense? So now, have in mind because it happened to me many times. When I was trying to change the header and it wasn't working, why is that or having a space there at the top of the file, for some reason, okay?
[00:09:09]
And that's all. Okay, so now, we have seen how to send messages or data between pages, from one page to the other page through POST or GET using the super global variables. [COUGH] And also we have another entry point called api.php that is using the same object crypto converter, the same object to render JSON.
Learn Straight from the Experts Who Shape the Modern Web
- In-depth Courses
- Industry Leading Experts
- Learning Paths
- Live Interactive Workshops