Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kittsville's avatar

Retrieving Headers from Response

Hi,

In order to test a REST API I'm trying to add an assertion that the Location header exists and points to the correct resource. I have checked Google, the Laravel documentation and the Laravel API but to no avail. Zend seems to have implemented methods to do this but I've found nothing for Lumen/Laravel. What I would like to be able to do:

<?php
/**
 * Tests that a Game instance can be created
 *
 * @return void
 */
public function testCreateGame()
{
    $response = $this->post('/api/v1/games/new');
    
    $this->assertResponseStatus(
        201,
        'HTTP response code for successful Game creation should be 201'
    );
    
    $response->seeJsonStructure([
        'id',
        'seed',
    ]);
    
    // Method name made up
    $this->assertHasResponseHeader('Location');
    
    // Allows other tests to use this test as their producer
    return $response->getResponseHeader('Location');
}
0 likes
4 replies
ohffs's avatar
ohffs
Best Answer
Level 50

I think (though haven't tested) that you can just do $location = $response->header('Location') to get it (or it's set to null if it's missing).

https://github.com/laravel/framework/blob/5.2/src/Illuminate/Http/Request.php#L512

Edit: doh! just noticed that was the request rather than the response. Sorry! Try doing a dd($response) to see what's there maybe?

Edit2 : apparently you can do things like :

$this->assertEquals('application/json', 
        $response->headers->get('Content-Type'));
4 likes
kittsville's avatar

Response also has a header method but unfortunately it only sets the headers. I tried dd($response) at the beginning and got ~9000 lines. The header is definitely there in both the raw response and as several arrays throughout the object. Unfortunately they're all protected arrays/objects.

kittsville's avatar

You were spot on with that 2nd edit!

It also turns out my code was incorrect because of:

<?php
$response = $this->post('/api/v1/games/new');

$this->post() doesn't return the Response instance (which I think call() would have) but instead the current test instance. The Response instance is stored in $this->response.

tl;dr my code should have been:

<?php
/**
 * Tests that a Game instance can be created
 *
 * @return void
 */
public function testCreateGame()
{
    $this->post('/api/v1/games/new');
    
    $this->assertResponseStatus(
        201,
        'HTTP response code for successful Game creation should be 201'
    );
    
    $this->seeJsonStructure([
        'id',
        'seed',
    ]);

    $this->assertTrue(
        $this->response->headers->has('Location'),
        'API response should have Location header'
    );
    
    // Allows other tests to use this test as their producer
    return $this->response->headers->get('Location');
}

Please or to participate in this conversation.