Courses

How to Build Laravel 12 API From Scratch

Why 404 Page? Setting Correct Headers

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Handling API 404 errors correctly
- Seeing different ways for setting proper API headers
- Customizing API error messages for better security

Video Version of the Lesson

[Only for premium members]

Link to the repository

[Only for premium members]

In this lesson, we will set one correct header value to avoid returning web pages instead of JSON results.


As you can see in the /api/categories/1, we see data for one category.

But what happens if we pass a missing category? We get an HTML page.

But for API, it is wrong. API expects the result as a JSON. In your client, set the headers to Accept -> application/json. Now Laravel knows to send the result as a JSON.

Another way is to set headers using Middleware. First, let's create a Middleware.

php artisan make:middleware AlwaysAcceptJson

Inside Middleware, we have a Request. Middleware is not just for preventing something; you can also add something...

The full lesson is only for Premium Members.
Want to access all 28 video+text lessons of this course? (1 h 21 min)

You also get:

  • 83 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord