Posts tagged with json

Here's one of the weirdest issue I have ever experienced with an API. Let's see, so I am using the Facebook Business API, and it works fine for most requests I do, however there are some accounts that behave very strange.

Let's see, if I call this:

accounts_general_fields = ['account_id', 'business_name', 'account_status', 'age', 'amount_spent','balance','currency'] print(me.get_ad_accounts(fields=accounts_general_fields)) 

this works fine, there is not issue, however when I want to iterative over it, for example

accounts= list(me.get_ad_accounts(fields=accounts_general_fields)) 
accounts= me.get_ad_accounts(fields=accounts_general_fields) accounts_fixed = [account.api_get(fields=accounts_general_fields) for account in accounts] 
accounts= me.get_ad_accounts(fields=accounts_general_fields) accounts_fixed = [account.export_all_data() for account in accounts] 

or

accounts= me.get_ad_accounts(fields=accounts_general_fields) accounts_fixed = [account for account in accounts] 

it gets this:

facebook_business.exceptions.FacebookRequestError:    Message: Call was not successful   Method:  GET   Path:    https://graph.facebook.com/v20.0/me/adaccounts   Params:  {'fields': 'account_id,business_name,account_status,age,amount_spent,balance,currency', 'summary': 'true', 'after': 'MjM4NDM4NDA2MTg4NjAxMjkZD'}   Status:  400   Response:     {       "error": {         "message": "(#80004) There have been too many calls to this ad-account. Wait a bit and try again. For more info, please refer to https://developers.facebook.com/docs/graph-api/overview/rate-limiting#ads-management.",         "type": "OAuthException",         "code": 80004,         "error_subcode": 2446079,         "fbtrace_id": "ArA51rxNPTHAl7CrHVCaEWG"       }     } 

This behavior happens with other endpoints, for example:

AdAccount(ad_account_id).get_campaigns(fields=fields) 

and

AdAccount(ad_account_id).get_campaigns(fields=fields) 

but just for specific ad accounts, like 3 or 4 accounts of 300 accounts. I don't know what could be happening. Here is my implementation for those endpoints:

 def fetch_adsets_for_account(ad_account_id, fields):     try:         return list(AdAccount(ad_account_id).get_ad_sets(fields=fields))     except Exception as e:         print(f"Failed to fetch ad sets for ad account {ad_account_id}: {e}")         return [] def fetch_adsets_data(ad_account_ids, fields):     all_data = []     # Use ThreadPoolExecutor to fetch data in parallel     with concurrent.futures.ThreadPoolExecutor(max_workers=30) as executor:         # Create a list of futures         futures = {executor.submit(fetch_adsets_for_account, ad_account_id, fields): ad_account_id for ad_account_id in ad_account_ids}         # As each future completes, append the result to all_data         for future in concurrent.futures.as_completed(futures):             try:                 data = future.result()                 all_data.extend(data)             except Exception as e:                 ad_account_id = futures[future]                 print(f"An error occurred for ad account {ad_account_id}: {e}")     # Convert the collected data to a DataFrame     df = pd.DataFrame(all_data)     return df #  Example usage: ad_account_ids = df_accounts["id"].tolist()[:] fields = ['name', 'status', 'start_time', 'lifetime_budget'] start = time.time() df_individual_adsets = fetch_adsets_data(ad_account_ids, fields) df_individual_adsets["date"] = today_data end = time.time() print(end - start) 

Here's one example of the problem for this:

Failed to fetch ad sets for ad account act_400136354038554:    Message: Call was not successful   Method:  GET   Path:    https://graph.facebook.com/v20.0/act_400136354038554/adsets   Params:  {'fields': 'name,status,start_time,lifetime_budget', 'summary': 'true', 'after': 'QVFIUmM2a3VXdG5XRG43OFd3ZAVdLNlV5d1BaR3NlWFlyTk9zQW5yaElIYWZAieVF0b3pFMUphV0tIZAmR4VEE2S3J0LTIZD'}   Status:  400   Response:     {       "error": {         "message": "User request limit reached",         "type": "OAuthException",         "is_transient": false,         "code": 17,         "error_subcode": 2446079,         "error_user_title": "Ad Account Has Too Many API Calls",         "error_user_msg": "There have been too many calls from this ad-account. Please wait a bit and try again.",         "fbtrace_id": "A-LW6ciS_vyN_vkhK5CD0tW"       }     } 

I'm encountering an inconsistency with accessing the Facebook Graph API. When making requests from my local IP address, I receive the expected JSON responses containing product data. However, attempts from my VPS IP address result in empty responses with no data returned. Here are the responses:

Local IP Response:

{   "data": [     {       "id": "*****",       "name": "4LAE 040 110 S04  (4*11*45L)",       "retailer_id": "ACBrg"     },     // More product data...   ],   "paging": {     "cursors": {       "before": "eyJvZAmZAzZAXQiOjB9",       "after": "eyJvZAmZAzZAXQiOjI0fQZDZD"     },     "next": "https://graph.facebook.com/v18.0/***************/products?access_token=...&pretty=1&limit=25&after=eyJvZAmZAzZAXQiOjI0fQZDZD",     "previous": "https://graph.facebook.com/v18.0/***************/products?access_token=...&pretty=1&limit=25&before=eyJvZAmZAzZAXQiOjB9"   } } 

VPS Response

{   "data": [] } 

Despite using the same URL (https://graph.facebook.com/v18.0/***************/products) and access token, the response from the VPS does not contain any product data. I have ensured that the URL, access token, and server configurations are correct. Any insights on why the VPS responses differ from those of my local IP and how to resolve this issue would be greatly appreciated."

I have a Flutter newsreader app that uses a WordPress JSON feed for its content. Im using Advanced Ads Wordpress plugin and its injecting the same ads that are on the web into the JSON Feed with the post content.

When my WebView loads it automatically spawns an external browser. This is without user interaction. The ads are loading fine in the webview. I had the same issue with youtube but applying the same solution to the google ads URL does not work.

import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:webview_flutter/webview_flutter.dart'; import 'package:url_launcher/url_launcher.dart'; import 'data.dart'; // Post model import 'html.dart'; // For building HTML content import 'package:share_plus/share_plus.dart'; // Import share_plus class PostDetailScreen extends StatefulWidget{   final Post post;   final List<Post> recentPosts;   const PostDetailScreen({Key? key, required this.post, required this.recentPosts}) : super(key: key);   @override   PostDetailScreenState createState() => PostDetailScreenState(); } class PostDetailScreenState extends State<PostDetailScreen>{   late WebViewController _controller;   String htmlContent = '';   bool isLoading = true;   @override   void initState() {     super.initState();     loadContent();   }   Future<void> loadContent() async {     String encodedVisbyFont = await loadEncodedFont();     String encodedCanelaFont = await loadCanelaFont();     htmlContent = buildHtmlContent(         widget.post.imageUrl,         widget.post.title,         widget.post.content,         widget.post.author,         widget.post.modified,         encodedVisbyFont,         encodedCanelaFont,         widget.recentPosts.take(10).toList()     );     setState(() {       isLoading = false;     });   }   Future<void> updatePostContent(String postLink) async {     final selectedPost = widget.recentPosts.firstWhere(           (post) => post.link == postLink,       orElse: () => widget.post,     );     String updatedContent = buildHtmlContent(       selectedPost.imageUrl,       selectedPost.title,       selectedPost.content,       selectedPost.author,       selectedPost.modified,       await loadEncodedFont(),       await loadCanelaFont(),       widget.recentPosts.take(10).toList(),     );     setState(() {       htmlContent = updatedContent;     });     _controller.loadUrl(Uri.dataFromString(       htmlContent,       mimeType: 'text/html',       encoding: Encoding.getByName('utf-8'),     ).toString());   }   @override   Widget build(BuildContext context) {     final bool tablet = MediaQuery.of(context).size.width > 600;     final double titleFontSize = tablet ? 36.0 : 24.0;     final double iconSize = tablet ? 36.0 : 30.0;     final EdgeInsetsGeometry iconPadding = tablet ? const EdgeInsets.all(12.0) : const EdgeInsets.all(8.0);     final double appBarHeight = tablet ? 70.0 : 56.0;     return Scaffold(       appBar: PreferredSize(         preferredSize: Size.fromHeight(appBarHeight),         child: AppBar(           title: Text(             'FRENCHLY',             style: TextStyle(               fontFamily: 'Oswald',               fontSize: titleFontSize,               fontWeight: FontWeight.bold,               color: Colors.white,             ),           ),           backgroundColor: const Color(0xFF1D5986),           centerTitle: true,           iconTheme: IconThemeData(color: Colors.white, size: iconSize),           actions: <Widget>[             Padding(               padding: iconPadding,               child: IconButton(                 icon: Icon(Icons.share, color: Colors.white, size: iconSize),                 onPressed: () {                   Share.share('${widget.post.title}\n\n${widget.post.link}');                 },               ),             ),           ],         ),       ),       body: isLoading           ? const Center(child: CircularProgressIndicator())           : WebView(         initialUrl: Uri.dataFromString(           htmlContent,           mimeType: 'text/html',           encoding: Encoding.getByName('utf-8'),         ).toString(),         javascriptMode: JavascriptMode.unrestricted,         onWebViewCreated: (WebViewController controller) {           _controller = controller;         },         navigationDelegate: (NavigationRequest request) async {           if (request.url.startsWith('post://')) {             final postLink = Uri.decodeFull(request.url.substring(7));             updatePostContent(postLink);             return NavigationDecision.prevent;           } else if (request.url.contains('youtube.com') || request.url.contains('youtu.be')) {             // Load YouTube URLs in the WebView itself             return NavigationDecision.navigate;           } else if (await canLaunchUrl(Uri.parse(request.url))) {             await launchUrl(Uri.parse(request.url), mode: LaunchMode.externalApplication);             return NavigationDecision.prevent;           }           return NavigationDecision.navigate;         },       ),     );   } } 

I'm trying to convert the below PQL query (Publisher's Query Language) in to JSON format.

StatementBuilder statementBuilder = new StatementBuilder()   .where("CUSTOM_CRITERIA LIKE '%permutive'") .withBindVariableValue("orderId", orderId); 

Can any one help with this ? Thanks in advance !

I am currently writing a chatbot for WhatsApp. I use the 360dialog platform, which makes it possible to work with the WhatsApp Business API.

When the client sends a message, I see the following JSON object in the logs of my application:

{     "messages": [         {             "from": "77773336633",             "id": "ABGGd3c1cGY_Ago61ytHsZknvtLv",             "image": {                 "id": "ffd23134-2dae-4fed-b5f8-0ce7867b6ddd",                 "mime_type": "image/jpeg",                 "sha256": "bd02100d961b5a1dbaae1dd645485ebbfeda77b44e82c015f1cf29b05654ccb9"             },             "timestamp": "1605703542",             "type": "image"         }     ],     "contacts": [         {             "profile": {                 "name": "Nurzhan Nogerbek"             },             "wa_id": "77773336633"         }     ] } 

I can't find any information in the documentation about how to download this file. In my case, I want to upload this image file that the client sends to my file storage. Please tell me which URL method from the WhatsApp API is responsible for this mechanism?

P.S. At the same time, I can send files to clients. This information is available on the official documentation.