Reputation: 86
I’m creating an API and I’m wondering if there is any way to pass data via an URL with a post method for example
add?name={name}&age={age}…
I don’t have much experience with API development, but I remember this URL thingy worked in Spring Boot.
Thanks in advance.
Upvotes: 0
Views: 772
Reputation: 3620
First of all, create a route that handles POST HTTP requests without any query parameter.
$app->post('/add', function (Request $request, Response $response, array $args) {
// get query parameters as an associative array
$params = $request->getQueryParams();
// return $params as a JSON data
$response->getBody()->write(json_encode($params));
return $response->withHeader('Content-Type', 'application/json');
});
Then, make a POST HTTP request to that route with your query parameters: /add?name=Foo&age=27
.
Output:
{
"name": "Foo",
"age": "27"
}
Upvotes: 1
Reputation: 2879
You can pass data in URL like that in any type of HTTP Request. That said when using POST / PUT / PATCH I would recommend using JSON payload sent as Request Body.
If you want to read an argument in Slim
<?php
$app->get('/hello/{name}', function (Request $request, Response $response, array $args) {
$name = $args['name'];
// or
$name = $request->getArgument('name');
// When Request URL is
// /hello/world?age=24
// you can read the age argument as
$name = $request->getArgument('age');
// This behaviour is defined in PSR-7 and available across PHP frameworks
return $response;
});
In plain PHP you can read an argument using superglobal $_GET or $_POST
<?php
$name = $_GET['age'];
Upvotes: 0