Response Payload incorrect using Youtube Data API - python

I'm trying to use Youtube's Data API to get some info on various channels, but when I run my build:
youtube = build('youtube', 'v3',developerKey=api_key)
request = youtube.channels().list(
part = "statistics",
forUsername = "tonetalks"
)
response = request.execute()
print(response)
It returns this:
{'kind': 'youtube#channelListResponse', 'etag': 'RuuXzTIr0OoDqI4S0RU6n4FqKEM', 'pageInfo': {'totalResults': 0, 'resultsPerPage': 5}}
Any thoughts how to fix this ?

The forUsername is incorrect. If you're looking for this "tonetalks" channel, you'll have to use its id UCfP8rCe_fAITriqI3UPYF0Q (from the above channel URL):
request = youtube.channels().list(
part = "statistics",
id = "UCfP8rCe_fAITriqI3UPYF0Q",
)
{
"kind": "youtube#channelListResponse",
"etag": "5gs56_i4Xd_fQ4A1OkQEnWWnX7A",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#channel",
"etag": "m7gogJwH4TshrBX4PCiuFP5MsJI",
"id": "UCfP8rCe_fAITriqI3UPYF0Q",
"statistics": {
"viewCount": "6033544",
"subscriberCount": "81200",
"hiddenSubscriberCount": false,
"videoCount": "229"
}
}
]
}

Related

API FedEX "INVALID.INPUT.EXCEPTION","message":"Invalid field value in the input"

I'm trying to validade an address in FedEX API using Python 3.8 and it returns an error of invalid field value
First I connect to the Auth API
payload={"grant_type": "client_credentials",'client_id':Client_id,'client_secret':Client_secret}
url = "https://apis-sandbox.fedex.com/oauth/token"
headers = {'Content-Type': "application/x-www-form-urlencoded"}
response=requests.post(url, data=(payload), headers=headers)
And it returns a message with the Auth token correctly
{"access_token":"eyJhbGciOiJSUzI1NiIsInRM5U0F2eUs1ZVFBVTFzS5k","token_type":"bearer","expires_in":3599,"scope":"CXS SECURE"}
Then I just get the token to use it in next transactions
token = json.loads(response.text)['access_token']
Then I prepare the next payload for address validation API
payload_valid_address = {
"addressesToValidate": [
{
"address":
{
"streetLines": ["7372 PARKRIDGE BLVD"],
"city": "Irving",
"stateOrProvinceCode": "TX",
"postalCode": "75063-8659",
"countryCode": "US"
}
}
]
}
And send the request to the new endpoint with the given token
url = "https://apis-sandbox.fedex.com/address/v1/addresses/resolve"
headers = {
'Content-Type': "application/json",
'X-locale': "en_US",
'Authorization': 'Bearer '+ token
}
response = requests.post(url, data=payload_valid_address, headers=headers)
print(response.text)
and get the error
<Response [422]>
{"transactionId":"50eae03e-0fec-4ec7-b068-d5c456b64fe5","errors":[{"code":"INVALID.INPUT.EXCEPTION","message":"Invalid field value in the input"}]}
I have made inumerous tests and I don't get the invalid field.
Anyone know what is happening and can help?
payload = json.dumps({input payload}) this works to prevent the response error 422
<Response [422]>
I have fixed it
For any reason, convert the string payload_valid_address to Json in 2 steps doesn't work
payload_valid_address = {....}
payload = json.dumps(payload_valid_address)
But if made in just one step it pass the API request
payload_valid_address = json.dumps({....})
I also had this error and additionally had to use json.loads(json_string) when the json data contained key words like false, true or null.
import json
json_string = r'''{
"accountNumber": {
"value": "802255209"
},
"requestedShipment": {
"shipper": {
"address": {
"postalCode": 75063,
"countryCode": "US"
}
},
"recipient": {
"address": {
"postalCode": "m1m1m1",
"countryCode": "CA"
}
},
"shipDateStamp": "2020-07-03",
"pickupType": "DROPOFF_AT_FEDEX_LOCATION",
"serviceType": "INTERNATIONAL_PRIORITY",
"rateRequestType": [
"LIST",
"ACCOUNT"
],
"customsClearanceDetail": {
"dutiesPayment": {
"paymentType": "SENDER",
"payor": {
"responsibleParty": null
}
},
"commodities": [
{
"description": "Camera",
"quantity": 1,
"quantityUnits": "PCS",
"weight": {
"units": "KG",
"value": 20
},
"customsValue": {
"amount": 100,
"currency": "USD"
}
}
]
},
"requestedPackageLineItems": [
{
"weight": {
"units": "KG",
"value": 20
}
}
]
}
}'''
data = json.loads(json_string)
data
response = requests.request("POST", url, data=json.dumps(data), headers=headers)
I have managed to get Fedex to accept my ayload, however i get this message:
"code":"INVALID.INPUT.EXCEPTION","message":"Validation failed for object='shipShipmentInputVO'. Error count: 1","parameterList":[{"key":"NotNull.shipShipmentInputVO.labelResponseOptions","value":"labelResponseOptions cannot be null"
and when I add the required parameter
'labelResponseOptions': "URL_ONLY"
I get this:
"code":"SYSTEM.UNEXPECTED.ERROR","message":"The system has experienced an unexpected problem and is unable to complete your request. Please try again later. We regret any inconvenience."
Is this really some Fedex internal error?

Fetching Comments using Youtube data API

Im trying to fetch all the comments for a particular Youtube video.
I've written the following code:
#storing all the comments in a list (l)
def video_comments(url):
# empty list for storing reply
replies = []
# creating youtube resource object
youtube = build('youtube', 'v3',
developerKey=api_key)
# retrieve youtube video results
video_response=youtube.commentThreads().list(
part='snippet,replies',
videoId=url
).execute()
for item in video_response['items']:
# Extracting comments
comment = item['snippet']['topLevelComment']['snippet']['textDisplay']
# counting number of reply of comment
replycount = item['snippet']['totalReplyCount']
# if reply is there
if replycount>0:
# iterate through all reply
for reply in item['replies']['comments']:
# Extract reply
reply = reply['snippet']['textDisplay']
# Store reply is list
replies.append(reply)
comment = remove_URL(comment)
# print comment with list of reply
l.append(comment)
for resp in replies:
resp = remove_URL(resp)
# print comment with list of replyprint(resp, replies, end = '\n\n')
l.append(comment)
# empty reply list
replies = []
video_comments(n)
However, the following code fetches only 20-25 comments even though that video has hundreds-thousands of comments.
The response has a nextPageToken attribute with its value - see the documentation, then, you have to use that token - in order to get the next results.
Try this example:
https://youtube.googleapis.com/youtube/v3/commentThreads?part=id%2Creplies%2Csnippet&maxResults=10&videoId=pf3kMUZvyE8&key=[YOUR_API_KEY]
Response: Note in the response the nextPageToken attribute.
{
"kind": "youtube#commentThreadListResponse",
"etag": "priyTHCuTXn9LlRkKazYailhGq0",
"nextPageToken": "QURTSl9pMlgzMi1IR0ZfTEtXZzNFRjQ1N3dEVmJlNXlPZ3BqUDFrMHlUejdxc3NIZFBOS013dWFRVjU5TWotWFJBaFJfUE1BSHR4aE9BQQ==",
"pageInfo": {
"totalResults": 9,
"resultsPerPage": 10
},
"items": [
{
"kind": "youtube#commentThread",
"etag": "MezAPCqHnXHD4xfxGWCKw8GwMrk",
"id": "Ugybh70lAXjKtWKnhVt4AaABAg",
"snippet": {
"videoId": "pf3kMUZvyE8",
"topLevelComment": {
"kind": "youtube#comment",
"etag": "MfJ5ylnOGfVyfNlVM7qc0mSwLJQ",
"id": "Ugybh70lAXjKtWKnhVt4AaABAg",
"snippet": {
"videoId": "pf3kMUZvyE8",
"textDisplay": "Electricity is raw energy",
"textOriginal": "Electricity is raw energy",
"authorDisplayName": "Kevinzhw Zhang wang",
"authorProfileImageUrl": "https://yt3.ggpht.com/ytc/AKedOLSU9_Tg183EZXdMmQbFcYKBw4WBajjPZc4gpT1W=s48-c-k-c0x00ffffff-no-rj",
"authorChannelUrl": "http://www.youtube.com/channel/UCBCwvesq011-2OP1mXq6t8w",
"authorChannelId": {
"value": "UCBCwvesq011-2OP1mXq6t8w"
},
"canRate": true,
"viewerRating": "none",
"likeCount": 0,
"publishedAt": "2021-12-24T05:59:47Z",
"updatedAt": "2021-12-24T05:59:47Z"
}
},
"canReply": true,
"totalReplyCount": 0,
"isPublic": true
}
},
{
"kind": "youtube#commentThread",
"etag": "fiwm5vdcDBQh_CtyzB05jqp3h68",
"id": "UgzoTdopkSulNGL_6tZ4AaABAg",
"snippet": {
"videoId": "pf3kMUZvyE8",
"topLevelComment": {
"kind": "youtube#comment",
"etag": "pCGjZzOYwkp7Z4bbhF_DiutwSow",
"id": "UgzoTdopkSulNGL_6tZ4AaABAg",
"snippet": {
"videoId": "pf3kMUZvyE8",
"textDisplay": "Yo no tengo autismo y si intenté eso XD",
"textOriginal": "Yo no tengo autismo y si intenté eso XD",
"authorDisplayName": "XXX DDD",
"authorProfileImageUrl": "https://yt3.ggpht.com/ytc/AKedOLTiD1hjwHmK8TWDil3XujkWfIFMvrc-_y0cTg=s48-c-k-c0x00ffffff-no-rj",
"authorChannelUrl": "http://www.youtube.com/channel/UCXarJ5GGpaBLaV1KEPimQXA",
"authorChannelId": {
"value": "UCXarJ5GGpaBLaV1KEPimQXA"
},
"canRate": true,
"viewerRating": "none",
"likeCount": 0,
"publishedAt": "2021-12-24T00:45:31Z",
"updatedAt": "2021-12-24T00:45:31Z"
}
},
"canReply": true,
"totalReplyCount": 0,
"isPublic": true
}
},
[other comments here...]
]
}

Flasgger - Add bearer authorization

I am running a flask app and using flasgger to generate Swagger Specs as well as a Swagger UI. My API requires the requests to be authenticated using a bearer token. I am able to get the button on the page and set the token. But it is not sent through the requests. I am using OpenAPI 3.0.3. Below is my code:
from flasgger import Swagger
swagger_template = {
'components': {
'securitySchemes': {
'bearerAuth': {
'type': 'http',
'scheme': 'bearer',
'bearerFormat': 'JWT'
}
},
'security': {
'bearerAuth': []
}
}
}
# Register controllers
api = Api(app)
swagger = Swagger(app=app, config={
'headers': [
],
'title': 'Model Design Application API',
'specs': [
{
'endpoint': 'apispec',
'route': '/apispec.json'
}
],
'openapi': '3.0.3'
}, template=swagger_template)
This is the token to be set in the Swagger UI:
This is the UI I get in Swagger:
This is the apispec.json that is generated:
{
"definitions": {
"User": {
"properties": {
"username": {
"default": "Steven Wilson",
"description": "The name of the user",
"type": "string"
}
}
}
},
"info": {
"description": "powered by Flasgger",
"termsOfService": "/tos",
"title": "Model Design Application API",
"version": "0.0.1"
},
"openapi": "3.0.3",
"paths": {
"/profile": {
"get": {
"description": "It works also with swag_from, schemas and spec_dict<br/>",
"responses": {
"200": {
"description": "A single user item",
"schema": {
"$ref": "#/definitions/User"
}
}
},
"summary": "This examples uses FlaskRESTful Resource"
}
}
},
"security": {
"bearerAuth": []
},
"securitySchemes": {
"bearerAuth": {
"bearerFormat": "JWT",
"scheme": "bearer",
"type": "http"
}
}
}
Please advice. Any help is appreciated.
For adding header in Flasgger API, do the following changes:
SWAGGER_TEMPLATE = {"securityDefinitions": {"APIKeyHeader": {"type": "apiKey", "name": "x-access-token", "in": "header"}}}
swagger = Swagger(app, template=SWAGGER_TEMPLATE)
Here, x-access-token is our key name in header. you can change this name according to your requirement.
After this, we need to add this header in our .yml file. Our .yml file will look like this:
summary: "Put your summery here."
description: "Put your description here."
consumes:
- "application/json"
produces:
- "application/json"
security:
- APIKeyHeader: ['x-access-token']
responses:
200:
description: "Success"
Check the working code here
template = {
"swagger": "2.0",
"info": {
"title": XYZ API Docs",
"description": "API Documentation for XYZ Application",
"contact": {
"responsibleOrganization": "",
"responsibleDeveloper": "",
"email": "XYZ#XYZ.com",
"url": "XYZ.com",
},
"termsOfService": "XYZ .com",
"version": "1.0"
},
"basePath": "/api/v1", # base bash for blueprint registration
"schemes": [
"http",
"https"
],
"securityDefinitions": {
"Bearer": {
"type": "apiKey",
"name": "Authorization",
"in": "header",
"description": "\
JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\""
}
},
"security": [
{
"Bearer": []
}
]
}
swagger_config = {
"headers": [
],
"specs": [
{
"endpoint": 'apispec',
"route": '/apispec.json',
"rule_filter": lambda rule: True, # all in
"model_filter": lambda tag: True, # all in
}
],
"static_url_path": "/flasgger_static",
"swagger_ui": True,
"specs_route": "/api/v1/apispec"
}

Getting a request error 422 upon get request

I have seen some posts about this but most of them used requests.post and I want a get request.
I am making a program that simply goes to a url and gets a list of orders.
This is the example response:
{
"page": 1,
"pageCount": 22,
"orderCount": 214,
"orders": [
{
"id": "c1497823-370c-4c7a-82cd-dacddb36fc30",
"productId": "1a641ba5-38df-4acb-86f7-f5c031e538a0",
"email": "demoemail#autobuy.io",
"ipAddress": "127.0.0.1",
"total": 18,
"currency": "USD",
"gateway": "Stripe",
"isComplete": true,
"createdAtUtc": "2019-10-15T01:44:10.5446599+00:00"
},
{
"id": "228f4ca4-5001-4c19-8350-f960f13d35a7",
"productId": "a0041cc0-2bc6-40a2-9084-5880bae5ecec",
"email": "demoemail#autobuy.io",
"ipAddress": "127.0.0.1",
"total": 50,
"currency": "USD",
"gateway": "Stripe",
"isComplete": true,
"createdAtUtc": "2019-10-15T01:43:17.8322919+00:00"
},
{
"id": "71aed9b2-4bd2-4a49-9e6a-82119e6e05bf",
"productId": "2e0ac75b-bfea-42f1-ad60-ead17825162a",
"email": "demoemail#autobuy.io",
"ipAddress": "127.0.0.1",
"total": 6,
"currency": "USD",
"gateway": "Stripe",
"isComplete": true,
"createdAtUtc": "2019-10-14T23:54:44.6217478+00:00"
}
]
}
This is what I get:
<Response [422]>
My code:
import requests
url = "https://autobuy.io/api/Orders?page=1"
headers = {
"Cache-Control": "no-cache",
"Pragma": "no-cache",
"APIKey": "<APIKEY>"
}
req = requests.get(url, headers=headers)
print(req)
Documentation for the api I'mtrying to use https://api.autobuy.io/?version=latest
edit: on their site it says
HEADERS
APIKey
2cdbdc48-b297-41ad-a234-329db0d2dbea
AutoBuy Api Key found in your shop settings
but then when I remove my Cache-Control and Pragma headers I get an error that has to do with my headers being cached (cause the site is behind a CDN?)
Ended up being a bug in the site, my dashboard was showing an invalid key.

How do i disable Facebook messenger persistent menu?

I recently enabled persistent_menu for my bot but now I want to disable it.
Below is how i enabled it
data={
"psid" : uid,
"persistent_menu" : [{
"locale" : "default",
"composer_input_disabled" : False,
"call_to_actions" : [
{
"type": "postback",
"title": "Request Ride",
"payload": "Request Ride"
},
{
"type": "postback",
"title": "Call Customer Service",
"payload": "Call"
},
]
}]
}
r = requests.post("https://graph.facebook.com/v6.0/me/custom_user_settings?access_token=<PAGE TOKEN>", data=json.dumps(data), headers={"Content-Type" : "application/json"})
To disable it, simply omit the call_to_actions field:
{
"psid": <PSID>,
"persistent_menu": [
{
"locale": "default",
"composer_input_disabled": false
}
]
}

Categories