Question

How to return a HTTP status code with PHP serverless function

I want to return a custom HTTP status code in a PHP serverless function. But the following code:

return ['body' => ['test'=>'Lorem ipsum'], 'statusCode' => 404];

Has this output (with HTTP status 200):

{"body":{"test":"Lorem ipsum"},"statusCode":404}

Expected output (with HTTP status 404):

{"test":"Lorem ipsum"}

Submit an answer
Answer a question...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

alexdo
Site Moderator
Site Moderator badge
March 7, 2023

hello @accountmorel

Here is a minimal example that the function returns an error repose along with an HTTP status code and additional HTTP headers:

  1. function main(): array {
  2. return [
  3. 'body' => 'The requested resource is not found.',
  4. 'statusCode' => 404,
  5. 'headers' => (object)
  6. [
  7. 'Cache-Control' => 'no-cache',
  8. ],
  9. ];
  10. }

You can find more information here:

https://www.digitalocean.com/community/tags/serverless

https://php.watch/articles/php-serverless-digital-ocean

Hope that this helps!