How to create a POST using RESTful API on PHP

Tiempo de lectura: < 1 minuto

Reading Time: < 1 minutes

Continuing from the previous post on How to create a GET using RESTful API on PHP, I’m going to show you how to create a POST and send JSON data using the body. Using RESTful API and the PHP programming language.

First of all:

  • Open your favorite code editor (Notepad++, Visual Studio Code, etc.).
  • Create a file and name it enviar_color.php.
  • Edit the file and add the following:
<?php

// POST:
// Get the body
$inputJSON = file_get_contents('php://input');
// Convert to JSON
$jsonObtenido= json_decode($inputJSON, TRUE);

$color = $jsonObtenido['color'];

?>

Now, let me explain the code that was added:

This line retrieves the content of the body from the HTTP request: $inputJSON = file_get_contents('php://input');

This line converts the content to JSON so we can use its data: $jsonObtenido= json_decode($inputJSON, TRUE);

And now, we can retrieve the ‘color’ key using this code:

$color = $jsonObtenido['color'];

With this, we have completed the backend part.

To test the code, we would need to send a POST request to the address https://localhost/enviar_color.php

In the body, add the following JSON:

{
"color": "green"
}

And that’s all for today.

Leave a Comment