How to register a custom REST API endpoint in WordPress?

I’m learning WordPress and want to create a custom REST API endpoint that returns JSON data. I read about the register_rest_route() function but I’m not sure where to put the code or how to test it properly.

Can someone give a basic example of creating a REST route in WordPress with authentication, and how to call it?

Thanks in advance!

I created a plugin and used register_rest_route() inside the init hook, but when I visit the route URL, it shows a 404 error. I’m not sure if I’m using the right hook or path.

I want a basic example to register a REST API route in WordPress that returns JSON like {“status”: “success”} and how to test it in the browser.