I am trying to access the elements within the text JSON reference from the call, for example, I am trying to access the item (content)
inside the JSON but it continues to show me the error message knowing
that the code works and the full text of the JSON file is displayed
without problems Is there a similar PHP lavarel method that can be
used as an arrylist Or any kind of data structure that is used to
obtain the elements within a response
$client = new Client();
$request = $client->post('http://localhost:4567/user/login', [
'headers' => ['Content-Type' => 'application/json'],
'body' => json_encode($data),
]);
$request= json_decode($request->getBody(), true);
return $request[0];
Your code should be like
use GuzzleHttp\Client;
$client = new Client();
$request = $client->post('http://localhost:4567/user/login', [
'headers' => ['Content-Type' => 'application/json'],
'body' => json_encode($data),
]);
return $request->getBody();
Related
I have create API of update my project details, I test it in POSTMAN app it shows the success message but there no effect in the database.
Here are my code:
ProjectsController.php
public function UpdateProject($id)
{
$data = Input::all();
$q = Project::where('id',$id)->update($data);
return response()->json([
'code' => SUCCESS,
'message' => 'Project data update successfully'
]);
}
api.php
Route::post('UpdateProject/{id}','ProjectsController#UpdateProject');
Postman - see image.
output in postman:
{
"code": "200",
"message": "Project data update successfylly"
}
Can anyone help me out?
Thank you
I think you need to check all input details closely , it also comes with token when you submit the form so you need to save all details except token
Change this
$data = Input::all();
to this
$data = Input::except('_token');
I hope this resolves the issue.
in your model add fillable :
protected $fillable = ['name', 'project_group_id','number','ROM','address','city','state','zip','start_date','end_date','duration','description','timeline_type','project_type_id','project_category_id','office_id'];
You have forgotten to run the ->save() method after updating the data:
public function UpdateProject($id)
{
$data = Input::all();
$q = Project::find($id)
$q = $q->fill($data);
$q->save();
return response()->json([
'code' => SUCCESS,
'message' => 'Project data update successfully'
]);
}
You can use this method it will reduce your code
Route (api)
Route::post('UpdateProject/{project}','ProjectsController#UpdateProject');
ProjectsController.php
public function UpdateProject(Request $request, Project $project)
{
$data = $request->all();
$project->update($data);
return response()->json([
'code' => SUCCESS,
'message' => 'Project data update successfully'
]);
}
I am trying to get sessionid by using ebay Trading API . I am able to get session id successfully by using Curl but as soon as i try to fetch session id via Guzzle Http client, get below error in response from ebay
FailureUnsupported API call.The API call "GeteBayOfficialTime" is
invalid or not supported in this release.2ErrorRequestError18131002
I suppose there's some issues with the way i am using GuzzleHttp client . I am currently using GuzzleHttp v6 and new to this . Below is the code i am using to get session id by calling actionTest function
public function actionTest(){
$requestBody1 = '<?xml version="1.0" encoding="utf-8" ?>';
$requestBody1 .= '<GetSessionIDRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
$requestBody1 .= '<Version>989</Version>';
$requestBody1 .= '<RuName>test_user-TestAs-Geforc-ldlnmtua</RuName>';
$requestBody1 .= '</GetSessionIDRequest>';
$headers = $this->getHeader();
$client = new Client();
$request = new Request('POST','https://api.sandbox.ebay.com/ws/api.dll',$headers,$requestBody1);
$response = $client->send($request);
/*$response = $client->post('https://api.sandbox.ebay.com/ws/api.dll', [
'headers' => $headers,
'body' => $requestBody1
]);*/
echo $response->getBody();die;
}
public function getHeader()
{
$header = array(
'Content-Type: text/xml',
'X-EBAY-API-COMPATIBILITY-LEVEL: 989',
'X-EBAY-API-DEV-NAME: a4d749e7-9b22-441e-8406-d3b65d95d41a',
'X-EBAY-API-APP-NAME: TestUs-GeforceI-SBX-345ed4578-10122cfa',
'X-EBAY-API-CERT-NAME: PRD-120145f62955-96aa-4d748-b1df-6bf4',
'X-EBAY-API-CALL-NAME: GetSessionID',
'X-EBAY-API-SITEID: 203',
);
return $header;
}
Plz suggest the possible shortcoming in the way i am making request . I already tried/modified the guzzle request call by referring various reference site and guzzle official doc but error remained same .
You need to pass an associative array of headers as explained in the documentation.
public function getHeader()
{
return [
'Content-Type' => 'text/xml',
'X-EBAY-API-COMPATIBILITY-LEVEL' => '989',
'X-EBAY-API-DEV-NAME' => '...',
'X-EBAY-API-APP-NAME' => '...',
'X-EBAY-API-CERT-NAME' => '...',
'X-EBAY-API-CALL-NAME' => '...',
'X-EBAY-API-SITEID' => '203',
];
}
In case you are interested there is an SDK available that simplifies the code. An example of how to call GetSessionID is shown below.
<?php
require __DIR__.'/vendor/autoload.php';
use \DTS\eBaySDK\Trading\Services\TradingService;
use \DTS\eBaySDK\Trading\Types\GetSessionIDRequestType;
$service = new TradingService([
'credentials' => [
'appId' => 'your-sandbox-app-id',
'certId' => 'your-sandbox-cert-id',
'devId' => 'your-sandbox-dev-id'
],
'siteId' => '203',
'apiVersion' => '989',
'sandbox' => true
]);
$request = new GetSessionIDRequestType();
$request->RuName = '...';
$response = $service->getSessionID($request);
echo $response->SessionID;
I have built an API and an application that uses that API. Everything was working but now, for some reason, I get a 400 Bad Request response. I am not sure if I changed something in the code so I wanted to double check it was correct.
So my API call is this
$client = new GuzzleHttp\Client();
$jsonData = json_encode($data);
$req = $client->request('POST', 'https://someurl.com/api/v1/createProject', [
'body' => $jsonData,
'headers' => [
'Content-Type' => 'application/json',
'Content-Length' => strlen($jsonData),
]
]);
$output = $req->getBody()->getContents();
The API has a route set up correctly which uses post. The function it calls is correct, and I have changed it for testing to simply return
return response()->json(["Success", 200]);
When I test the API out within Postman, I can see that Success is returned. When I test the API within the other application I have built, I dont even see a POST request within the console, I am just displayed a Laravel error 400 Bad Request.
What could be the cause of this issue?
Thanks
Update
I have changed the request to this
$data= json_encode($data);
$req = $client->post('https://someurl.com/api/v1/createProject', [
'body' => $data
]);
If I output $data after it has been encoded, I get something like this
{
"projectName":"New Project",
"clientName":"Test Client",
}
Within the controller function of the API that is being called, I simply do
return response()->json(['name' => $request->input('clientName')]);
The 400 error has now gone, but I now get null returned to me
{#326 ▼
+"name": null
}
Request is being injected into the function as it should be. Should I be returning the data in a different way?
Thanks
Probably you did $ composer update and Guzzle updated.
So if you are using newest Guzzle (guzzlehttp/guzzle (6.2.2)) you do POST request:
$client = new GuzzleHttp\Client();
$data = ['name' => 'Agent Smith'];
$response = $client->post('http://example.dev/neo', [
'json' => $data
]);
You do not need to specify headers.
To read response you do following:
$json_response = json_decode($response->getBody());
My full example (in routes file web.php routes.php)
Route::get('smith', function () {
$client = new GuzzleHttp\Client();
$data = ['name' => 'Agent Smith'];
$response = $client->post('http://example.dev/neo', [
'json' => $data,
]);
$code = $response->getStatusCode();
$result = json_decode($response->getBody());
dd($code, $result);
});
Route::post('neo', function (\Illuminate\Http\Request $request) {
return response()->json(['name' => $request->input('name')]);
});
or you could use following (shortened), but code above is "shorter"
$json_data = json_encode(['name' => 'Agent Smith']);
$response = $client->post('http://example.dev/neo', [
'body' => $json_data,
'headers' => [
'Content-Type' => 'application/json',
'Content-Length' => strlen($json_data),
]
]);
note: If you are running PHP5.6, change always_populate_raw_post_data to -1 (or uncomment the line) in php.ini and restart your server. Read more here.
In my case I was using public IP address in BASE_URL while I should have been using the private IP. From mac you can get your IP by going into system preferences -> network.
This is with Android + Laravel (API)
I get data from server:
store = new dojox.data.QueryReadStore({"url":"http://url_with_data"});
...
myGrid = new dojox.grid.DataGrid({"id":"myGrid2","selectionMode":"none","style":"height: 350px; width: 100%;","store":store,"structure":myGrid2Layout}), document.createElement('div');
In this example server must return json object where exists property "items", and this property contains all data. Example(php):
$a = array(
'items' => array(....)
);
echo json_encode($a);
The problem is that my server returns json with slightly different structure, like it:
$a = array(
'result' => array(
'items' => array(....)
);
);
echo json_encode($a);
How to solve this problem?
You can extend the QueryReadStore and override the _filterResponse function to manipulate the data you get back from the server.
dojo.declare("myQrs", [dojox.data.QueryReadStore], {
_filterResponse: function(data) {
//process/massage your data here
return data
}
});
See: http://trac.dojotoolkit.org/browser/dojo/tags/release-1.5.0/dojox/data/QueryReadStore.js and search for _filterResponse for some notes on this
I'm writing functional test and i need to make ajax post request. "The CSRF token is invalid. Please try to resubmit the form". How can i get the token in my functional test ?
$crawler = $this->client->request(
'POST',
$url,
array(
'element_add' => array(
'_token' => '????',
'name' => 'bla',
)
),
array(),
array('HTTP_X-Requested-With' => 'XMLHttpRequest')
);
CSRF token generator is normal symfony 2 service. You can get service and generate token yourself. For example:
$csrfToken = $client->getContainer()->get('form.csrf_provider')->generateCsrfToken('registration');
$crawler = $client->request('POST', '/ajax/register', array(
'fos_user_registration_form' => array(
'_token' => $csrfToken,
'username' => 'samplelogin',
'email' => 'sample#fake.pl',
'plainPassword' => array(
'first' => 'somepass',
'second' => 'somepass',
),
'name' => 'sampleuser',
'type' => 'DSWP',
),
));
The generateCsrfToken gets one important parameter intention which should be the same in the test and in the form otherwise it fails.
After a long search (i've found nothing in doc and on the net about how to retrieve csrf token) i found a way:
$extract = $this->crawler->filter('input[name="element_add[_token]"]')
->extract(array('value'));
$csrf_token = $extract[0];
Extract the token from response before make the request.
In symfony 3, in your WebTestCase, you need to get the CSRF token:
$csrfToken = $client->getContainer()->get('security.csrf.token_manager')->getToken($csrfTokenId);
To get the $csrfTokenId, the best way would be to force it in the options of your FormType ():
class TaskType extends AbstractType
{
// ...
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'csrf_token_id' => 'task_item',
));
}
// ...
}
So in this case: $csrfTokenId = "task_item";. Or you you can try to use the default value, that would be the name of your form.
Then use it as a post parameter:
$client->request(
'POST',
'/url',
[
'formName' => [
'field' => 'value',
'field2' => 'value2',
'_token' => $csrfToken
]
]
);
Just in case someone stumble on this, in symfony 5 you get the token this way:
$client->getContainer()->get('security.csrf.token_manager')->getToken('token-id')->getValue();
where 'token-id' is the id that you used in the configureOptions method in your form type, which would look something like this:
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
"data_class" => Foo::class,
"csrf_protection" => true,
"csrf_field_name" => "field_name", //form field name where token will be placed. If left empty, this will default to _token
"csrf_token_id" => "token-id", //This is the token id you must use to get the token value in your test
]);
}
Then you just put the token in the request as a normal field.