API key not valid for google cloud translate - google-api

require_once ('vendor/autoload.php');
use Google\Cloud\Translate\TranslateClient;
/** Uncomment and populate these variables in your code */
$text = 'The text to translate.';
$targetLanguage = 'hi'; // Language to translate to
$translate = new TranslateClient();
$result = $translate->translate($text, [
'target' => $targetLanguage,
'key'=>'&key=KEY_REAL',
]);
print("Source language: $result[source]\n");
print("Translation: $result[text]\n");
use Google\Cloud\Translate\V3\TranslationServiceClient;
$translationServiceClient = new TranslationServiceClient();
/** Uncomment and populate these variables in your code */
$text = 'This is a test. Hello, world!';
$targetLanguage = 'fr';
$projectId = 'dev-antler-288108';
$contents = $text;
$formattedParent = $translationServiceClient->locationName($projectId, 'global');
try {
$response = $translationServiceClient->translateText(
$contents,
$targetLanguage,
$formattedParent
);
// Display the translation for each input text provided
foreach ($response->getTranslations() as $translation) {
printf('Translated text: %s' . PHP_EOL, $translation->getTranslatedText());
}
} finally {
$translationServiceClient->close();
}
This is the code and when i run this i get
Message: { "error": { "code": 400, "message": "API key not valid.
Please pass a valid API key.", "errors": [ { "message": "API key not
valid. Please pass a valid API key.", "domain": "global", "reason":
"badRequest" } ], "status": "INVALID_ARGUMENT" } }
is there something i am doing wrong here ???

Related

SMS Alert API Validation in laravel

public function verifyotp(Request $request)
{
$mobile=$request->mobilenumber;
$otp=$request->otp;
$client = new \GuzzleHttp\Client();
$tem='https://www.smsalert.co.in/api/mverify.json?apikey=#&mobileno=';
$cod='&code=';
$msg=($tem.$mobile.$cod.$otp);
$res=$client->request('POST', $msg);
(string) $res->getBody();
if($res->getBody(['description']=== "['desc']:Code does not match.")
{
echo 'Code Not Matched';
}
elseif(($res->getBody(['description'] === "['desc']:Code Matched successfully."))
{
echo 'Code Matched;
}
}
I have get response from api.I got Two response
one is like this
{
"status": "success",
"description": {
"desc": "Code does not match."
}
}
Second like this
{
"status": "success",
"description": {
"desc": "Code matched successfully." }
}
In This response i want to read "desc" on my controller
How to check desc using if condition ?
You can use json_decode function like this :
$result = json_decode($response);
echo $result->description->desc;
see this for detail
Done...

Uploading file to onedrive using microsoft graph api

I am trying to uploading a video file to onedrive using the microsoft graph api with the php sdk implementation in laravel.
Code details as below
// Get the access token from the cache
$tokenCache = new TokenCache();
$accessToken = $tokenCache->getAccessToken();
$file_name = 'new_video.mp4';
$media_path = storage_path('video.mp4');
// Create a Graph client
$graph = new Graph();
$graph->setAccessToken($accessToken);
//create post request
$postData = json_encode([ 'items' =>
[
"#odata.type" => "microsoft.graph.driveItemUploadableProperties",
"#microsoft.graph.conflictBehavior" => "rename",
"name" => $file_name
]
]);
//dd(json_encode($postData));
try {
$post = $graph->createRequest('POST', '/drive/root/:{item-path}:/createUploadSession')->attachBody($postData)->upload($media_path);
} catch (\Illuminate\Http\Client\RequestException $e) {
dd($e);
}
Not sure what should go into the item path too, i tried using the folder name but got error and i also tried excluding the item path but still got an error.
This is the error I am getting
Client error: `POST https://graph.microsoft.com/v1.0/drive/root/createUploadSession` resulted in a `400 Bad Request` response: {
"error": {
"code": "BadRequest",
"message": "Unable to read JSON request payload. Please ensure Content-T (truncated...)
Json Encode of the request data is also as below and I cant figure out the problem...
{"items":
{
"#odata.type":"microsoft.graph.driveItemUploadableProperties",
"#microsoft.graph.conflictBehavior":"rename",
"name":"new_video.mp4"
}
}
According to this example given on msgraph-sdk-php repository you don't need to json_econde your body data. The sdk will do it for you.
So your code should looks like this:
// Get the access token from the cache
$tokenCache = new TokenCache();
$accessToken = $tokenCache->getAccessToken();
$file_name = 'new_video.mp4';
$media_path = storage_path('video.mp4');
// Create a Graph client
$graph = new Graph();
$graph->setAccessToken($accessToken);
//create post request
$postData = [ 'items' =>
[
"#odata.type" => "microsoft.graph.driveItemUploadableProperties",
"#microsoft.graph.conflictBehavior" => "rename",
"name" => $file_name
]
];
try {
$post = $graph->createRequest('POST', '/drive/root/:{item-path}:/createUploadSession')->attachBody($postData)->upload($media_path);
} catch (\Illuminate\Http\Client\RequestException $e) {
dd($e);
}

Validating json data for unique fields in laravel

I have a json request with household_data. I have tried to use validator on family_no which is a unique field. the json I'm working on is :
[
{
"BasicInfo": {
"ward": "12",
"tole_name": "Sahayogi Nagar",
"house_no": "21",
"family_no": "420",
"district": "Lalitpur",
},
"Family": [
{
"caste": "bahun",
"religion": "hindu",
}
]
}]
But the validator fails always, even if the family_no is unique or not and returns:
{
"family_no": [
"The family no field is required."
]
}
here is my controller code:
$items = json_decode($request->household_data);
// return json_decode($request->household_data);
if($request->household_data){
$validator = Validator::make($items, [
'family_no' => 'required|unique:households|max:255',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 404);
}
else{
foreach($items as $key=>$item){
$householdId = $this->saveHousehold($item);
return $householdId;
}
}
}
Anyone could please help me validate the unique field family_no?
checkout array validator of laravel on the doc webiste https://laravel.com/docs/7.x/validation#validating-arrays. But for your validation you have to write it like this :
{
"BasicInfo.family_no": [
"The family no field is required."
]
}

Laravel Json Response Not working as expected

Unable to get response while response object is empty. Works perfect when the object has data returned.
public function show($id)
{
$associates = Associate::find_by_id($id);
if(count($associates)<1)
{
$output = array('message' => 'No Records Found');
$status = 204;
}
else{
$output = array('message' => 'success','data'=>$associates);
$status = 200;
}
return response()->json($output,$status);
}
There is no response when the $associate object is empty.
Response when $associate is not empty:
{
"message": "success",
"data": [
{
"first_name": "xxx",
"last_name": "xxx",
"mobile": xxxxxxxxxx,
"email": "xxxxxx#xxxxx",
"city": "xxxxx",
"state": "xxxxxx",
"pincode": "xxxxx"
}
]
}
I had the same issue for status code 204 .
I believe this is caused here. The Illuminate\Foundation\Application class is then catching this and throwing an HttpException.
I believe the simplest fix would be to make the controller return the following instead:
return Response::make("", 204);
Returning a empty message.
check status_code in your code to display message in frontend .
It will be easier if you use route model binding to find the ID of the record. For more information check https://laravel.com/docs/5.7/routing#route-model-binding.
I think the snippet below should work.
if ($associates) {
$output = array('message' => 'success','data'=>$associates);
$status = 200;
} else {
$output = array('message' => 'No Records Found');
$status = 204;
}
I've rewrote the function for your reference.
BTW. If the function return only one record, use singular noun for variable name in general.
public function show($id)
{
// Use find() instead of find_by_id()
$associate = Associate::find($id);
// $associate will be null if not matching any record.
if (is_null($associate)) {
// If $associate is null, return error message right away.
return response()->json([
'message' => 'No Records Found',
], 204);
}
// Or return matches data at the end.
return response()->json([
'message' => 'success',
'data' => $associate,
], 204);
}

Laravel API - Vue.js returning Posts with user

I am trying to learn Vue.js that consumes an API build with Laravel. The idea is simple, a user can make a post and a post can have comments. I can get the relationships working within laravel, but I can not figure out how to return the author name of the post or comment with Vue.js.
When using the blade templating engine I use something like this in a foreach loop for returning the Author name:
{{ $post->user->name }}
When I return the posts trough an API I get don't get any user information, except for the user id. How can I get the user information that belongs to this post?
{
"message": "Success",
"data": [
{
"id": 1,
"body": "test body 1",
"user_id": "1",
"created_at": "2016-09-16 10:22:57",
"updated_at": "2016-09-16 10:22:57"
}
]
}
<script>
export default {
/*
* The component's data.
*/
data() {
return {
posts: [],
};
},
/**
* Prepare the component.
*/
ready() {
this.getPosts();
},
methods: {
/**
* Get Posts.
*/
getPosts: function() {
this.$http.get('/api/wall/posts')
.then(response => {
this.posts = response.data.posts;
});
}
}
}
</script>
public function getPosts($id = null)
{
if (!$id){
$data = Post::all();
$message = 'Success';
$code = 200;
} else {
$data = Post::FindOrFail($id);
$message = 'Success';
$code = 200;
}
return Response::json(['message' => $message, 'data' => $data], $code);
}
You may use eager loading for that:
Post::with('user')->FindOrFail($id);

Resources