Good morning.
I'm currently trying to access the POST data from a curl request in a Symfony 4 Controller.
My controller looks like the following:
class OrderController extends AbstractController
{
/**
* #Route("/order", name="order")
*/
public function index(Request $request)
{
var_dump($request->request->all());die;
return $this->json([
'message' => 'Welcome to your new controller!',
'path' => 'src/Controller/OrderController.php',
]);
}
}
When I run php bin\console server:run and access the localhost/order in the browser I get the page it is supposed to get. If I curl the url with
curl http://127.0.0.1:8000/order
I also get the right results. But when I try to send a json body on the curl request, on the above controller I just get an empty array.
My request looks like the following:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST -d '
{'json':{
"id": "1",
"customer-id": "1",
"items": [
{
"product-id": "B102",
"quantity": "10",
"unit-price": "4.99",
"total": "49.90"
}
],
"total": "49.90"
}}' http://127.0.0.1:8000/order
Any idea on what am I doing wrong?
The Request object will only return form parameters via $request->request methods. if you want to access the JSON body, you need to use $request->getContent(). If that content is json, your code will look something like this:
$json = json_decode($request->getContent(), true);
var_dump($json['json']);
Related
I'm working on a project and I came across a problem, explain:
I'm doing a POST to a webserver using the Guzzle http, follows the :
public function sendPost($direction, array $data, array
$options = ['http_errors'=>false])
{
$url = $this->interpolate( self::BASE_PATH."/{direction}",
[
'direction' => $direction
]);
$options = array_merge($options,['body'=>json_encode($data)]);
return $this->client->post($url, $options);
}
The method is working correctly and I am returning the following:
{
"id": "jdhj9h830027hd73hs9q9js9",
"direction": "left",
"status": "Success",
"code": {
"id":"1",
"desc": "ok",
"error": false,
"msg":null
}
}
What I can not do is the following:
A method that returns only the given "jdhj9h830027hd73hs9q9js9", that is, the "id" parameter.
can anybody help me?
PS. By using the "sendPost ()" method I can access the data I need separately, however I can not do this through another method, such as a "getId ()".
Thank you in advance for your help.
Just try:
return ($this->client->post($url, $options))->id;
In my routes file I have
Route::post('/request-rest-password', 'HomeController#requestResetPwd');
IN the controller
public function requestResetPwd(Request $request){
return $request;
}
Now whenever I try post it always throws an error
"exception":
"Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException","file":
"/var/www/html/freelancer/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php",
Where could I be going wrong
Example of a post
$ curl -X POST -H "Accept: application/json" -F "email=test#test.com" -F .......
"http://localhost:8000/request-reset-pwd"
You have a typo:
Route: request-rest-password
POST: request-reset-pwd
Route::post('/request-rest-password', 'HomeController#requestResetPwd')->name('post_insert');
and your form html should contain route like this ...
<form method="post" action="{{route('post_insert')}}">
{{csrf_field()}}
your user fields goes here...
</form>
If a user is attempting to access the REST api without proper credentials, my yii application throws the 401 error like this in my controller.php file:
throw new UnauthorizedHttpException('Access unavailable without access_token.', 401);
Which returns the error in this format:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<name>Unauthorized</name><message>Access unavailable.</message>
<code>401</code>
<status>401</status>
<type>yii\web\UnauthorizedHttpException</type>
</response>
How to I return this error in JSON format ?
{
"name": "Access unavailable.",
"message": "You are not authorized.",
"code": 0,
"status": 401
}
My mobile app accessing this resource expects a JSON object.
Try adding this above the return or better in your custom __construct.
Yii::$app->response->format = 'json';
yii2 rest controller reacts on the "Accept" HTTP Header. If in this header is only "application/json" present, the answer from rest controller will be JSON
this worked for me. Extend the activeController and i put it in api\controllers\ActiveController.php
namespace api\controllers;
class ActiveController extends yii\rest\ActiveController {
public function behaviors() {
$behaviors = parent::behaviors();
$behaviors['contentNegotiator'] = [
'class' => 'yii\filters\ContentNegotiator',
'formats' => [
'application/json' => \yii\web\Response::FORMAT_JSON,
]
];
return $behaviors;
}
}
then in my controller
use api\controllers\ActiveController;
class blablaController extends ActiveController
{
...
}
now on unauthorized i get a JSON instead of an XML
{"success":false,"data":{"name":"Unauthorized","message":"Your request was made with invalid credentials.","code":0,"status":401}}
For my rest api I use yii\rest\Controller
class TweetController extends Controller
{
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
'auth' => [$this, 'auth']
];
$behaviors['contentNegotiator'] = [
'class' => ContentNegotiator::className(),
'formats' => [
'application\json' => Response::FORMAT_JSON,
]
];
return $behaviors;
}
// not solved yet
public function auth($pass)
{}
/**
* #param int $count
*
* #return array
* #throws \yii\base\InvalidConfigException
*/
public function actionLastTweets($count = 10)
{
/**
* #var TweetLastfinder $tweetLastFinder
*/
$tweetLastFinder = Yii::$app->get('tweetlastfinder');
return $tweetLastFinder->findLastTweets($count);
}
also i use prettyUrls 'GET tweet/last-tweets/<count>' => 'tweet/last-tweets'
actionLastTweets return array which one convert into json.
Idea is made simply authentication. In docs is example how to implements IdentityInterface in model. But i don`t work with AR directly. As i understand. I need to properly write auth() method.
I dont get it, whith value should be returned from auth() when authentification is passed? And how it will be send by request? (i mean http://localhost/index.php/tweet/last-tweets/50 without authentication, how it change?)
For simplicity there is a string value $password = 'qwerty' and i want to check if parameter $pass equal $password - authentication passed
some kinda:
public function auth($pass)
{
$password = 'qwerty';
if ($pass == $password) {
authentication passed
} else {
authentication failed
}
}
The subject of the authentication is your Identity (aka user) that has to implements the funtion findIdentityByAccessToken
see
\yii\web\IdentityInterface
to try your API on command line you can use cUrl as follows ( the token: XXXXXXXX_accessTokenString_XXXXXX )
note, the ":" divides user from password in the basic autentication, the token is used as user
POST a JSON to MessageController (the pluralization is not an error)
curl --user "XXXXXXXX_accessTokenString_XXXXXX:" -H "Accept:application/json" -H "Content-Type:application/json" -XPOST "http://rest.my-domain.com/messages" -d '{"email": "me#example.com"}'
POST a JSON to UserController enabling xdebug
curl --user "XXXXXXXX_accessTokenString_XXXXXX:" --cookie 'XDEBUG_SESSION=1221221' -H "Accept:application/json" -H "Content-Type:application/json" -XPOST "http://rest.my-domain.com/messages" -d '{"email": "me#example.com"}'
GET a JSON to UserController enabling xdebug
curl --user "XXXXXXXX_accessTokenString_XXXXXX:" -H "Accept:application/json" -H "Content-Type:application/json" -XGET "http://rest.my-domain.com/messages/123"
see also the Yii2 guide to REST services
http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html
I have a route that does a POST to create data and I'm trying to test if everything should be working the way it should be.
I have a json string that will have the values that i want to test but so far the test is always failing when I run the test using phpunit:
Also,I know the json string is just a string but I'm also unsure of how to use the json string to test for input.
my route:
Route::post('/flyer', 'flyersController#store');
public function testFlyersCreation()
{
$this->call('POST', 'flyers');
//Create test json string
$json = '{ "name": "Test1", "email": "test#gmail.com", "contact": "11113333" }';
var_dump(json_decode($json));
}
When i run phpunit, my error points to the call POST that says "undefined index: name"
I'm not sure if i understand the question correctly, given the code example that actually does nothing, but if you're asking how to test a post route which requires json data in the request, take a look at the call() method:
https://github.com/laravel/framework/blob/4.2/src/Illuminate/Foundation/Testing/ApplicationTrait.php
raw post data should be in the $content variable.
I don't have Laravel 4 installed to test it, but it works for me in Laravel 5, where the function has just slightly different order of params:
public function testCreateUser()
{
$json = '
{
"email" : "horst.fuchs#example.com",
"first_name" : "Horst",
"last_name" : "Fuchs"
}';
$response = $this->call('POST', 'user/create', array(), array(), array(), array(), $json);
$this->assertResponseOk();
}
If you look at the source code of TestCase you can see that the method is actually calling
call_user_func_array(array($this->client, 'request'), func_get_args());
So this means you can do something like this
$this->client->request('POST', 'flyers', $json );
and then you check the response with
$this->assertEquals($json, $this->client->getResponse());
The error you are getting is probably thrown by the controller because it doesnt receive any data