Courses

How to Build Laravel 11 API From Scratch

Why 404 Page? Setting Correct Headers

Summary of this lesson:
- Handling API 404 errors correctly
- Seeing different ways for setting proper API headers
- Customizing API error messages for better security

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 23 lessons of this course? (58 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord