HttpError 400 when requesting on Youtube commentThreads: Check the structure of the <code>commentThread</code> resource in the request body - http

I am tying to access my comments on other videos. But I didn't understand that what is wrong with the request. I put youtube.force-ssl scope.
(Pdb) request = self.service.commentThreads().list(part="id,replies,snippet", channelId="UCxz_B5DVTdZV5c0JLctjqUA")
INFO __init__.py line:49 2022-09-19 21:23:55,044 - file_cache is only supported with oauth2client<4.0.0
(Pdb) request.execute()
*** googleapiclient.errors.HttpError: <HttpError 400 when requesting https://youtube.googleapis.com/youtube/v3/commentThreads?part=id%2Creplies%2Csnippet&channelId=UCxz_B5DVTdZV5c0JLctjqUA&alt=json returned "The API server failed to successfully process the request. While this can be a transient error, it usually indicates that the request's input is invalid. Check the structure of the <code>commentThread</code> resource in the request body to ensure that it is valid.". Details: "[{'message': "The API server failed to successfully process the request. While this can be a transient error, it usually indicates that the request's input is invalid. Check the structure of the <code>commentThread</code> resource in the request body to ensure that it is valid.", 'domain': 'youtube.commentThread', 'reason': 'processingFailure', 'location': 'body', 'locationType': 'other'}]">
(Pdb) request.headers
{'accept': 'application/json', 'accept-encoding': 'gzip, deflate', 'user-agent': '(gzip)', 'x-goog-api-client': 'gdcl/2.52.0 gl-python/3.8.10', 'content-length': '0'}
(Pdb) request.uri
'https://youtube.googleapis.com/youtube/v3/commentThreads?part=id%2Creplies%2Csnippet&channelId=UCxz_B5DVTdZV5c0JLctjqUA&alt=json'
(Pdb) request.body
(Pdb) request.to_json()
'{"uri": "https://youtube.googleapis.com/youtube/v3/commentThreads?part=id%2Creplies%2Csnippet&channelId=UCxz_B5DVTdZV5c0JLctjqUA&alt=json", "method": "GET", "body": null, "headers": {"accept": "application/json", "accept-encoding": "gzip, deflate", "user-agent": "(gzip)", "x-goog-api-client": "gdcl/2.52.0 gl-python/3.8.10", "content-length": "0"}, "methodId": "youtube.commentThreads.list", "resumable": null, "response_callbacks": [], "_in_error_state": false, "body_size": 0, "resumable_uri": null, "resumable_progress": 0}'
(Pdb) request.body
On the other hand lines below return a valid 200 response.
(Pdb) request=self.service.commentThreads().list(part="id,replies,snippet", allThreadsRelatedToChannelId="UCxz_B5DVTdZV5c0JLctjqUA")
INFO __init__.py line:49 2022-09-19 22:06:17,504 - file_cache is only supported with oauth2client<4.0.0
(Pdb) request.execute()
I have enabled Youtube Data API and give youtube.force-ssl scope again on Google Cloud console but I am not sure that am I have to give any other permissions. According to the doc. channelId should be a valid argument but I didn't understand why it returns 400 error if I gave channelId.
Weirdest thing is that even the same example on Google's documentation does not work.
However if I give my channel's id with allThreadsRelatedToChannelId argument it returns a HTTP 200 responseas expected.

They had removed channelId parameter :( https://issuetracker.google.com/issues/247966553

Related

Pact provider test returning 400 response on Windows but passing on OSX

I am trying out sample code here https://github.com/DiUS/pact-workshop-dotnet-core-v3 with PactNet - 4.3.0. The only change I have made to the sample code is that i am not working with provider states in the test and instead have the required state set as part of controller only.
While it works fine on OSX when i try it on windows (Windows Server 2019 Standard) I get the following error -
PactNet.Exceptions.PactFailureException: Pact verification failed
PactNet.Exceptions.PactFailureException
Pact verification failed
at PactNet.Verifier.InteropVerifierProvider.Execute()
at PactNet.Verifier.PactVerifierSource.Verify()
at tests.ProductApiTestsWithoutBroker.EnsureProviderApiHonoursPactWithConsumer() in C:\repos\ProofOfConcepts\Pact-Product-api\ProviderTests\ProductApiTestsWithoutBroker.cs:line 47
at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
at System.Reflection.MethodInvoker.Invoke(Object obj, IntPtr* args, BindingFlags invokeAttr)
Getting to pact verification
Starting verification...
Pact verification failed
Verifier Output
---------------
Verifying a pact between ApiClient and ProductService
A valid request for all products
returns a response which
has status code 200 (FAILED)
includes headers
"Content-Type" with value "application/json; charset=utf-8" (FAILED)
has a matching body (FAILED)
Failures:
1) Verifying a pact between ApiClient and ProductService - A valid request for all products
1.1) has a matching body
expected 'application/json;charset=utf-8' body but was 'text/html'
1.2) has status code 200
expected 200 but was 400
1.3) includes header 'Content-Type' with value 'application/json; charset=utf-8'
Expected header 'Content-Type' to have value 'application/json; charset=utf-8' but was 'text/html'
There were 1 pact failures
Verifier Logs
-------------
2023-02-14T20:36:14.433512Z INFO ThreadId(33) pact_verifier: Running provider verification for 'A valid request for all products'
2023-02-14T20:36:14.433752Z INFO ThreadId(33) pact_verifier::provider_client: Sending request to provider at http://localhost:9001/
2023-02-14T20:36:14.433771Z INFO ThreadId(33) pact_verifier::provider_client: Sending request HTTP Request ( method: GET, path: /api/products, query: None, headers: None, body: Missing )
2023-02-14T20:36:14.456312Z INFO ThreadId(33) pact_verifier::provider_client: Received response: HTTP Response ( status: 400, headers: Some({"cache-control": ["no-store"], "via": ["1.1 ForcepointCGCluster"], "date": ["Tue", "14 Feb 2023 20:36:32 GMT"], "content-type": ["text/html"], "connection": ["close"], "content-language": ["en"], "content-length": ["666"]}), body: Present(666 bytes, text/html) )
2023-02-14T20:36:14.456421Z INFO ThreadId(33) pact_matching: comparing to expected response: HTTP Response ( status: 200, headers: Some({"Content-Type": ["application/json; charset=utf-8"]}), body: Present(130 bytes) )
2023-02-14T20:36:14.457552Z WARN ThreadId(33) pact_matching::metrics:
Please note:
We are tracking events anonymously to gather important usage statistics like Pact version and operating system. To disable tracking, set the 'PACT_DO_NOT_TRACK' environment variable to 'true'.
2023-02-14T20:36:14.495312Z WARN ThreadId(33) rustls::conn: Sending fatal alert DecodeError
I am using .NET 7 and i tried including PactNet.Windows nuget package but it did not help. Also does not look like long Windows path issue to me here. Any pointers would be very helpful here. Thanks in advance,
Solution:
Update PactNet package to the latest version.
Check the configuration of the environment in which you are running the tests. Ensure that the Content-Type and Content-Encoding headers are set correctly in the response.
Check the code of the API to make sure it is returning the correct response headers and body.

NextJS, fetch, multipart/form-data, missing boundary

I've faced with issue while proxy http request with multipart form data by NextJS. I have to send file from a client fide to next js, after that - to FastApi service.
The problem was:
fetch("https://127.0.0.1:3000/api/newfile", {
method: "POST",
headers: { "Content-Type": "multipart/form-data" },
body: new FormData(form)
});
headers request: "Content-Type: multipart/form-data"
In order for NextJS API to parse the file, you need a header with boundary
Something like this:
multipart/form-data; boundary=----< generate boundary >
For a long time I could not figure out how to get it.
There is an exit. It is necessary not to fill in "Content-Type".
And then the browser itself will generate this header by passing the form-data.
For example:
fetch("https://127.0.0.1:3000/api/newfile", {
method: "POST",
headers: {},
body: new FormData(form)
});
I also noticed that the problem concerns fetch
When I used XMLHttpRequest I didn't face such problem.
Further, the header can easily be passed further to FastAPI
in API:
req.headers["content-type"]

Sending Fax by RingCentral API

I was trying to use fax API of RingCentral on Sandbox URL using REST client:
https://platform.devtest.ringcentral.com/restapi/v1.0/account/~/extension/~/fax
with following:
Authorization: Bearer {{my access_token}}"
Content-Type: application/json
{
"to": [{
"phoneNumber": "<my phone number>"
}],
"faxResolution": "High",
"sendTime": "2019-02-20T09:30:10.800Z"
}
But getting Bad Request issue from the fax API:
status code=400 content type=application/json;
{
"message": "Bad Request",
"errors": []
}
The issue clearly shows the contentType or fax MIME body...
Since the fax api support attachments as data. 400 Bad request error is caused due to wrong content or mime type
Content-Type: multipart/mixed
The API allows sending a fax message with a multipart request, incorporating two or more parts.
ref: https://developers.ringcentral.com/api-reference#
Following reference has described the same:
https://forums.developers.ringcentral.com/questions/517/weird-boundary-in-presence-response-when-requestin.html
https://forums.developers.ringcentral.com/questions/614/switching-to-f-form-option-for-posting-multipartmi.html?page=2&pageSize=10&sort=oldest

Access token request results in 302 in Angular HttpClient

I'm trying to authenticate requests for WordPress rest-api using grant type password. OAuth2 authentication in WordPress is provided by WP OAuth Server plugin.
When I request access token using Postman Chrome app the server responds with expected access token object but the similar request doesn't work in Angular. It gives status 302 and due to xhr redirect to login page, I'm not able to get access token object. I'm using Angular 5.
Here's how I request access token in Angular:
/* Example token url
AuthProvider.TOKEN_URL:
https://www.example-wordpress.com/oauth/token
*/
const body = {
grant_type: 'password',
username: username,
password: password,
};
const headers = new HttpHeaders()
.set('Authorization', 'Basic ' + btoa(AuthProvider.CLIENT_ID + ':' + AuthProvider.CLIENT_SECRET));
this.http.post(AuthProvider.TOKEN_URL, body, { headers: headers });
The above request produces 302 with location header set to:
https://www.example-wordpress.com/login/?redirect_to=https%3A%2F%2Fwww.example-wordpress.com%2Foauth%2Ftoken
And then a xhr GET request is made to above location which responds with HTML of login page and hence no access token is obtained.
The similar POST request for access token in Postman works fine and results in expected access token object but I can't get it to work in Angular.
EDIT
While debugging I generated JavaScript code for access token request from Postman and pasted in console of Chrome after importing jQuery.
The request works as expected in console as well and no redirection occurs. The response is JSON with access token.
Here's the code Postman generated for the POST request:
var settings = {
"async": true,
"crossDomain": true,
"url": "https://example-wordpress.com/oauth/token",
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded",
"authorization": "Basic M0wzakE3d080VmxxbXB0UUF1dUI5RkxicWxmeE8yR25Zdk4xQmxvbTp4TktTYnJ1Mno5cEp2VDFMbTNGNFhEQm10eDZzUGsya1FqZDg3VmQ2",
"cache-control": "no-cache",
"postman-token": "46339abe-2d1a-1032-f5d8-36e3193d9a81"
},
"data": {
"grant_type": "password",
"username": "my-username",
"password": "my-password",
"client_id": "3L3jA7wO4VlqmptQAuuB9FLbqlfxO2GnYvN1Blom",
"client_secret": "xNKSbru2z9pJvT1Lm3F4XDBmtx6sPk2kQjd87Vd6"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
And here's the response logged from above code:
{
access_token: "rksen3p351fj0povsrpfv2eeuahrciglc3ilphhy",
expires_in: 3600,
token_type: "Bearer",
scope: "basic",
refresh_token: "fudju8tecbnwly2e1xgfv92tykvpsniwkfpvrd7d"
}
I'm unable to figure out why redirection occurs when we request through Angular and not responds with access token JSON.
Any help is appreciated.
access_token (which I imagine is what you expect to have) isn't part of the few headers that Angular is able to read without setting up your server.
Angular only read "basic" headers such as Content-type. This is because of the default CORS configuration that only reads Cache-Control, Content-Language, Content-Type, Expires, Last-Modified and Pragma. When it comes to custom headers, you have to tell your server to expose the headers.
This is done through the Access-Control-Expose-Headers header.
There was no problem at all. It was a very very silly mistake. I apologize.
I was testing with two websites simultaneously and both had similar configuration. The only difference was that one had OAuth plugin installed and other not. So when I tried to authorize the request from Angular with the website which hadn't had OAuth2 plugin installed and so redirected to the login page. The constant set for the AuthProvider.TOKEN_URL was incorrectly set, while when I was testing with other tools I was using correct url.
Anyway, this was all my mistake. It happens sometimes, when you don't take break. :)

Uber API - requests endpoint cannot read read json

I am trying to generate a POST request for the requests endpoint in the following python code:
import requests
...
response = requests.post(
'https://sandbox-api.uber.com/v1/requests',
headers = {
'Authorization': 'Bearer %s' % access_token,
'Content-Type': 'application/json'
},
params={"start_latitude":"37.334381","start_longitude":"-121.89432","end_latitude":"37.77703","end_longitude":"-122.419571","product_id":"a1111c8c-c720-46c3-8534-2fcdd730040d"})
data = response.json()
The access_token was obtained using request scope during authorization. The response json is :
{"message": "Unable to parse JSON in request body.", "code": "invalid_json"}
Need help in formatting the request properly. Thanks.
Figured out the problem - had to replace the params field with a data field and wrap the dict with json.dumps() before sending it off.

Resources