Search code examples
phpresthttp-headerscodeigniter-2codeigniter-restserver

how to add a location header to http response from codeigniter rest server


I have a codeigniter rest api, created using this library: https://github.com/chriskacerguis/codeigniter-restserver

For my POST method, once the resource has been successfully created, I would like to include a location header that includes a URI to GET the newly created / updated resource. It's not clear to me how to do this. Has anyone tried something similar?

So far, I'm just adding the details of what's been created to the response body... but I would ultimately like to add the GET url as a location header.

This is what my logic looks like so far:

public function widget_post()
{
        $new_widget_data = array(
                'location'  =>$this->post('location'),
                'name'   => $this->post('name'),
                'cost'   => $this->post('cost')
                );

        // validate post data
        if (!$this->isvalidpost($new_widget_data)) {
                $this->response("Invalid data",400);
        }

        // add to database
        $res = $this->widget_model->notify_servers($new_widget_data);
        $new_widget_data['results']=$res;
        if ($res) {
                //append GET url to return value                    
                $new_widget_data['GET']=base_url()."/index.php/widgets/widget/".$new_widget_data['name'];
                $this->response($new_widget_data,201); //HTTP Created 201           
        } else {
        $this->response("Unable to process request",500); //HTTP Internal server error
        }

Any suggestions would be appreciated. Thanks.


Solution

  • I don't believe the current version of the library provides a way to do this.

    One option you have is to use the php header() function in conjunction with the response() function provided by the REST_Controller class.

    header("Location: location/to/new/resource");

    Then call the response function, ensuring you set the 201 code. $this->response($new_widget_data, 201);

    Typically the Location header will trigger a redirect by default, so ensure you always set the 201 code.

    http://php.net/manual/en/function.header.php