Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning http status codes with a rest api

I am building my own rest api in php for practice. I can evaluate the http code sent to my api (post,put,delete,get). But when I send out my response I really am just printing out a json. For example, I build a response in my api like this

    public function actionTest()
    {
        $rtn=array("id":"3","name":"John");
        print json_encode($rtn);
    }

I am not manipulating the headers in anyway. From reading stackoverflow, I understand that I should be returning http response codes to match my api results. How can I build on my api and return the response codes. I just don't understand how I can do it because right now I am just printing out a json.

I am not asking which codes to return. I just want to know how to return codes in general.

like image 673
Gilberg Avatar asked Jan 18 '14 16:01

Gilberg


People also ask

Which HTTP status code is returned after a successful REST API request?

The create action is usually implemented via HTTPs POST method. In RESTful APIs, these endpoints are used to create new resources or access tokens. 200 OK - It's the basic status code to tell the client everything went good.

How do I return status codes in spring rest?

Spring provides a few primary ways to return custom status codes from its Controller classes: using a ResponseEntity. using the @ResponseStatus annotation on exception classes, and. using the @ControllerAdvice and @ExceptionHandler annotations.

Which annotation is used for returning HTTP status code?

The @ResponseStatus annotation can be used on any method that returns back a response to the client.


1 Answers

You could re-think your code this way

public function actionTest()
{
    try {
        // Here: everything went ok. So before returning JSON, you can setup HTTP status code too
        $rtn = array("id", "3", "name", "John");
        http_response_code(200);
        print json_encode($rtn);
    }
    catch (SomeException $ex) {
        $rtn = array("id", "3", "error", "something wrong happened");
        http_response_code(500);
        print json_encode($rtn);
    }
}

Basically, before stream the output (the JSON data), you can set the HTTP status code by http_response_code($code) function.

And about your additional question in comment, yes, printing the JSON data is the correct way.

like image 174
Eddie C. Avatar answered Sep 21 '22 02:09

Eddie C.