I have:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use GuzzleHttp\Client;
class GetBlahCommand extends Command {
protected $name = 'blah:blah';
protected $description = "name";
public function handle()
{
$client = new Client();
$res = $client->request('GET', 'https://someapi.com', [
'api_key' => ['privatekey']
]);
echo $res->getStatusCode();
}
}
But the param api_key isn't being passed along.
How can I get this to work?
I have adjusted my code, but now I am getting NULL returned:
$ndbnos = [
'ndbno' => '01009'
];
$client = new Client(['base_uri' => 'https://soemapi.com']);
$res = $client->request('GET', '/', [
'query' => array_merge([
'api_key' => 'somekey'
], $ndbnos)
])->getBody();
$res = json_decode($res);
var_dump($res);
I figured it out:
public function handle()
{
$ndbnos = [
'ndbno' => '01009'
];
$client = new Client(['base_uri' => 'https://someapi.com']);
$res = $client->request('GET', '', [
'query' => array_merge([
'api_key' => 'somekey',
'format' => 'json'
], $ndbnos)
]);
print_r(json_decode($res->getBody()));
}
You can be do it by the following way:
public function handle()
{
$client = new Client(['base_uri' => 'https://someapi.com/']);
$res = $client->request('GET', '/', [
'headers' => [
'api_key' => 'YOUR_KEY'
]
]);
}
I thought it's a header parameter. If it's a form input you can do it by the following way:
public function handle()
{
$client = new Client(['base_uri' => 'https://someapi.com/']);
$res = $client->request('GET', '/', [
'query' => [
'api_key' => 'YOUR_KEY'
]
]);
}
Related
I am trying to generate a pdf with DOMPDF. This is my code:
class PDFController extends Controller
{
public function invoice(Request $request) {
// $institution = $this->institution();
// $user = $this->user();
$invoice = array($this->invoice_form($request));
$pdf = PDF::loadView('pdf-generation.invoice', $invoice);
return $pdf->setPaper('a4', 'landscape')->download('invoice.pdf');
//return view('pdf-generation.invoice')->with(['institution' => $institution, 'user' => $user, 'invoice' => $invoice]);
}
public function institution() {
$institution = Institution::where('id', 1)->get()->first();
return $institution;
}
public function user() {
$user = Auth::user();
return $user;
}
public function invoice_form(Request $request) {
$this->validate($request, array(
'furnizor-select' => 'required',
'document-number' => 'required',
'document-date' => 'required',
'due-date' => 'required',
'discount-procent' => 'required',
'discount-value' => 'required',
'total-value' => 'required',
'nir-number' => 'nullable'
));
$invoice = new \App\Models\Invoice();
$invoice->provider_id = $request->input('furnizor-select');
$invoice->number = $request->input('document-number');
$invoice->document_date = $request->input('document-date');
$invoice->due_date = $request->input('due-date');
$invoice->discount_procent = $request->input('discount-procent');
$invoice->discount_value = $request->input('discount-value');
$invoice->total = $request->input('total-value');
$invoice->save();
$invoices = Invoice::all();
$invoice_id = $invoices->last()->id;
$old_date = $request->input('document-date');
$new_date = date("d-m-Y", strtotime($old_date));
$provider_id = $request->input('furnizor-select');
$provider = Provider::where('id', $provider_id)->get();
$invoice_number = $request->input('document-number');
$old_due_date = $request->input('due-date');
$new_due_date = date("d-m-Y", strtotime($old_due_date));
$filename = 'pdfs/nir'.$invoice_id.'.pdf';
$institution = $this->institution();
$user = $this->user();
$array = array(
'invoice_id' => $invoice_id,
'new_date' => $new_date,
'provider' => $provider,
'invoice_number' => $invoice_number,
'due_date' => $new_due_date,
'provider' => $provider,
'institution' => $institution,
'user' => $user
);
return (object) $array;
}
}
And in my pdf-generation.invoice view, I have some html generate but it is not worth to post it all, so I am going to post only one line to give you some idea about the problem:
<span style="font-weight: bold; float: left;">{{$invoice->institution}}</span>
However, it says Undefined variable $invoice.. what could be the problem?
You can compact your variable like this:
$pdf = PDF::loadView('pdf-generation.invoice', compact('invoice'));
I want to pass the id from the controller to route but I'm having trouble with it. I am a newbie at this so I would really appreciate your help!
Controller:
public function fetchVideo(Request $request)
{
$client = new Client();
$input = $request->all();
$headers = [
'Authorization' => 'Bearer '.$input['token'],
'Content-type' => 'application/json',
'Accept' => 'application/json'
];
$params = [
'id' => $input['id'],
'fields' => $input['fields']
];
$response = $client->request ('GET', 'https://api.dailymotion.com/video/{id}', [
'headers' => $headers,
'query' => $params
]);
return json_decode($response->getBody(), true);
}
Route:
Route::post('/video/{id}', 'App\Http\Controllers\dailymotionController#fetchVideo');
public function fetchVideo(Request $request, $id) // <- {id} parameter in the route
{
...
$response = $client->request('GET', "https://api.dailymotion.com/video/{$id}", [...])
...
}
I am trying to write a test to mock an S3 upload which generates a pre-signed url.
Here is my test:
public function test_it_uploads_to_s3()
{
Storage::fake('s3');
$response = $this->json('POST', route('api.presignedUpload', 1), [
'name' => 'file.txt',
]);
$response->assertStatus(200)
->assertJsonStructure(['url']);
}
I'm getting the following error:
Call to undefined method League\Flysystem\Adapter\Local::getClient()
I thought I only needed to add the Storage::fake('s3'); part and it should mock S3 or am I mistaken?
Edit:
The controller function code:
$s3 = Storage::disk('s3');
$client = $s3->getDriver()->getAdapter()->getClient();
$cmd = $client->getCommand('PutObject', [
'Bucket' => \Config::get('s3.bucket'),
'Key' => 'files/' . $request->name,
'ACL' => 'private',
]);
$request = $client->createPresignedRequest($cmd, $this->expiry);
$presignedUrl = (string)$request->getUri();
return response()->json(['url' => $presignedUrl], 201);
I am not sure about the error you're getting with only this context but it seems that you're missing some code according to the Laravel 8.x docs for this:
public function test_it_uploads_to_s3() {
Storage::fake('s3');
$response = $this->json('POST', route('api.presignedUpload', 1), [
UploadedFile::fake()->file('file.txt')
]);
Storage::disk('s3')->assertExists('file.txt');
$response->assertStatus(200)->assertJsonStructure(['url']);
}
You can mock the filesystem and test this out.
use Illuminate\Support\Facades\Storage;
use Mockery;
protected static function mockPresignedUrl()
{
$storage = Mockery::mock('League\Flysystem\Adapter\Local');
$storage->shouldReceive('getAdapter')->andReturn($storage)
->shouldReceive('getClient')->andReturn($storage)
->shouldReceive('getBucket')->andReturn('s3')
->shouldReceive('getCommand')->andReturn($storage)
->shouldReceive('createPresignedRequest')->andReturn($storage)
->shouldReceive('getUri')->andReturn('https://some-presigned-url');
return $storage;
}
public function test_it_uploads_to_s3()
{
$storage = $this->mockPresignedUrl();
Storage::set('s3', $storage);
$this->putJson(route('api.presignedUpload', 1), [
'name' => 'file.txt',
])
->assertStatus(200)
->assertJson([
'url' => 'https://some-presigned-url'
]);
}
I am posting an image to my API using "guzzlehttp/guzzle": "6.3". When I post image to my API, I get false when I check for the file using hasFile(). Could it be that the file is not being submitted to my API?
Controller
$client = new Client();
$url = 'http://localhost:9000/api';
$path = 'app/public/images/';
$name = '94.jpeg';
$myBody['fileinfo'] = ['449232323023'];
$myBody['image'] = file_get_contents($path.$name);
$request = $client->post($url, ['form_params' => $myBody]);
$response = $request->getBody();
return $response;
API
if (!$request->hasFile('image')) {
return response()->json([
'message' => 'No file',
'photo' => $request->hasFile('image'),
'photo_size' => $request->file('image')->getSize()
]);
}
You'll need to add your form_params to the multipart array:
// untested code
$client = new Client();
$endpoint = 'http://localhost:9000/api';
$filename = '94.jpeg';
$image = public_path('images/' . $filename);
$request = $client->post($endpoint, [
'multipart' => [
[
'name' => 'fileinfo',
'contents' => '449232323023',
],
[
'name' => 'file',
'contents' => fopen($image, 'r'),
],
],
]);
$response = $request->getBody();
return $response;
I am having issues with the following part of my code using graphql-php libraries.
'resolve' =>function($value,$args,$context)
When I run the query:
"http://localhost:8080/index.php?query={certificate(id:"123ecd"){id}}"
I get the below listed message:
{"errors":[{"message":"Internal server error","category":"internal",
"locations":[{"line":1,"column":2}],"path":["certificate"]}],"data":{"certificate":null}}
Secondly when I run a nested query
"http://192.168.211.15:8080/index.php?query{certificates{id,products{id}}}"
I get the below listed response:
{"errors":[{"message":"Internal server error","category":"internal","locations":[{"line":1,"column":26}],"path":["certificates",0,"products"]}
"data":{"certificates":[{"id":"a023gavcx","status":"Valid","products":null}]}}
Below is my complete code:
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\ResolveInfo;
class CertificateType extends ObjectType{
public function __construct(){
$config = [
'name' => 'Certificate',
'fields' => function() {
return [
'id' => [
'type' => Types::nonNull(Types::string()),
],
'number' => [
'type' => Types::int()
],
'first_issue_date' => [
'type' => Types::string()
],
'products' => [
'type' => Types::product(),
'resolve'=> function($value, $args, $context){
$pdo = $context['pdo'];
$cert_id = $value->id;
$result = $pdo->query("select * from products where cert_id = {$cert_id} ");
return $result->fetchObject() ?: null;
}
]
];
}
];
parent::__construct($config);
}
}
use GraphQL\Type\Definition\Type;
class Types extends Type{
protected static $typeInstances = [];
public static function certificate(){
return static::getInstance(CertificateType::class);
}
public static function product(){
return static::getInstance(ProductType::class);
}
protected static function getInstance($class, $arg = null){
if (!isset(static::$typeInstances[$class])) {
$type = new $class($arg);
static::$typeInstances[$class] = $type;
}
return static::$typeInstances[$class];
}
}
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\ResolveInfo;
class ProductType extends ObjectType
{
public function __construct()
{
$config = [
'name' => 'Product',
'fields' => function() {
return [
'id' => [
'type' => Types::nonNull(Types::string()),
],
'primary_activity' => [
'type' => Types::string()
],
'trade_name' => [
'type' => Types::string()
],
];
},
];
parent::__construct($config);
}
}
require_once __DIR__ . '/../../../../autoload.php';
use GraphQL\GraphQL;
use GraphQL\Type\Schema;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
define('BASE_URL', 'http://127.0.0.1:8080');
ini_set('display_errors', 0);
$debug = !empty($_GET['debug']);
if ($debug) {
$phpErrors = [];
set_error_handler(function($severity, $message, $file, $line) use (&$phpErrors) {
$phpErrors[] = new ErrorException($message, 0, $severity, $file, $line);
});
}
try {
$dbHost = 'localhost';
$dbName = '*******';
$dbUsername = 'root';
$dbPassword = '*********';
$pdo = new PDO("mysql:host={$dbHost};dbname={$dbName}", $dbUsername, $dbPassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$appContext = [
'pdo' => $pdo ];
if (isset($_SERVER['CONTENT_TYPE']) && strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false) {
$raw = file_get_contents('php://input') ?: '';
$data = json_decode($raw, true);
} else {
$data = $_REQUEST;
}
$data += ['query' => null, 'variables' => null];
if (null === $data['query']) {
$data['query'] = '{hello}';
}
require __DIR__ . '/types/CertificateType.php';
require __DIR__ . '/types/ProductType.php';
require __DIR__ . '/types/OrganizationType.php';
require __DIR__ . '/Types.php';
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'hello' => [
'description' => ' Hello world',
'type' => Types::string(),
'resolve' => function() {
return 'Hello World';
}
],
'certificate' => [
'type' => Types::listOf(Types::certificate()),
'description' => 'This is the certificate identification',
'args' => [
'id' => Types::string()],
'resolve' => function ($rootValue,$args,$context) {
$pdo = $context['pdo'];
$id = $args['id'];
return $pdo->query("SELECT * from certificates where id ={$id}");
return $data->fetchObject() ?: null;
}
],
'certificates' => [
'type' => Types::listOf(Types::certificate()),
'resolve' => function($rootValue, $args, $context) {
$pdo = $context['pdo'];
$result = $pdo->query("select * from certificates order by id limit 10");
return $result->fetchAll(PDO::FETCH_OBJ);
}
],
]
]);
$schema = new Schema([
'query' => $queryType
]);
$result = GraphQL::execute(
$schema,
$data['query'],
null,
$appContext,
(array) $data['variables']
);
if ($debug && !empty($phpErrors)) {
$result['extensions']['phpErrors'] = array_map(
['GraphQL\Error\FormattedError', 'createFromPHPError'],
$phpErrors
);
}
$httpStatus = 200;
} catch (\Exception $error) {
// Handling Exception
// *************************************
$httpStatus = 500;
if (!empty($_GET['debug'])) {
$result['extensions']['exception'] = FormattedError::createFromException($error);
} else {
$result['errors'] = [FormattedError::create('Unexpected Error')];
}
}
header('Content-Type: application/json', true, $httpStatus);
echo json_encode($result);
Can somebody help me resolve these issues. Thanks in advance