Showing posts with label api. Show all posts
Showing posts with label api. Show all posts

Monday, September 27, 2021

Flutter - Fetch data from the internet | Network Request | Fetch and display the data with Flutter | Networking in Flutter using the http package | How to point to localhost:8000 with the Dart http package in Flutter

Today we will try to fetch the data from an API into a Flutter app.
Firstly, we need to import the http package, which provides the simplest way to fetch data from the internet into our project.

Update your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  http: # add this yours
Future is a core Dart class for working with async operations. A Future object represents a potential value or error that will be available at some time in the future.

The http.Response class contains the data received from a successful http call.

Although it’s convenient, it’s not recommended to put an API call in a build() method.

Flutter calls the build() method every time it needs to change anything in the view, and this happens surprisingly often. Leaving the fetch call in your build() method floods the API with unnecessary calls and slows down your app.

The http.get() method is used to make a request to the specified ‘url’ and http.Response class contains the data received from a successful http call. We make this function of type Future because we will get the response for the request at some time in the future, not immediately.

Future<http.Response> fetchPost() {
  return http.get('https://base.url/api/account/get/x0303');
}
Usually, the returning response will have information about the status of the request call, which can be accessed using response.statusCode.

import 'package:http/http.dart' as http;
Future<Object> fetchPost() async {
  final response = await http.get(Uri.parse('https://base.url/api/account/get/x0303'));

  if (response.statusCode == 200) {
    print(" Status: OK")
	return json.decode(response.body);
  }
  else {
    throw Exception('Failed to get data');
  }
}
Full example is as below

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: ApplicationBase(),
    );
  }
}

class ApplicationBase extends StatefulWidget {
  const ApplicationBase({Key? key}) : super(key: key);

  @override
  _ApplicationBaseState createState() => _ApplicationBaseState();
}

class _ApplicationBaseState extends State<ApplicationBase> {
  @override
  void initState() {
    super.initState();
  }

  Future<String> _calculation = Future<String>.delayed(
    Duration(seconds: 2), () => loadDataAsync(),
  );

  // flutter thread to load data
  static Future<String> loadDataAsync() async {
    return Future.delayed(Duration(seconds: 0), () async {
      final response = await http.get(Uri.parse('https://base.url/api/account/get/x0303'));

      if (response.statusCode == 200) {
        var data = json.decode(response.body);
        return data["result"] == null ? throw Exception(data["error"].toString()) : data["result"];
      }
      else {
        throw Exception('Failed to get data');
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    //_onPressed(context);
    return Scaffold(
      appBar: AppBar(
        title: Text("My Test App"),
      ),
      body: Center(
          child: FutureBuilder<String>(
            future: _calculation,
            builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
              List<Widget> children;

              if (snapshot.hasData) {
                children = <Widget>[
                  Text("Data loaded from http call = ${snapshot.data}")
                ];
              }
              else if (snapshot.hasError) {
                children = <Widget>[
                  Icon(
                    Icons.error_outline,
                    color: Colors.red,
                    size: 60,
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 16),
                    child: Text('Error: ${snapshot.error}'),
                  )
                ];
              }
              else {
                children = <Widget>[
                  SizedBox(height: 20),
                  SizedBox(
                    child: CircularProgressIndicator(),
                    width: 60,
                    height: 60,
                  ),
                  const Padding(
                    padding: EdgeInsets.only(top: 16),
                    child: Text('Awaiting result...'),
                  )
                ];
              }
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: children,
                ),
              );
            }
          )
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => const ApplicationBase()),
          );
        },
        child: Icon(Icons.add),
      ),
    );
  }
}
For test purpose, if you want to call your localhost from Flutter then do the below:

replace 'localhost' in your url to wifi connection ip e.g : 'http://localhost:8000' => 'http://192.168.1.102:8000'. you can get your wifi ip from command prompt with cmd>ipconfig (wireless LAN adapter WI-FI.

Sample screen shot


Thursday, September 5, 2013

Setup Remote Access Key cPanel Server WHM

Setup Remote Access Key

For WHM version 11.36 
(Home >> Cluster/Remote Access >> Setup Remote Access Key
This feature can be used to generate an access key. This access key can be used for automatic account creation scripts, external billing software, and allowing servers in your DNS cluster to exchange records. 
To generate a new access key: 
  1. Login to your_cpanel_server.com:2087 (example)
  2. Go to: Home>>Cluster/Remote Access>>Setup Remote Access Key
  3. Click Generate New Key.
  4. Copy and paste the new access key to the appropriate file on the remote server(s) that need to communicate with your web server. To use the remote access key to configure a DNS server cluster, follow our steps for configuring a cluster, pasting the key in on the Create Trust Relationshipscreen.

ACCESS HASH AUTHENTICATION

You can write your script so that it includes an access hash, or "key," in the HTTP header that it sends to the server when it calls the API function. This method is only available to WHM users. 
The access hash can be set up, and subsequently accessed, from the WHM Setup Remote Access Key feature. On your server, the hash resides in/root/.accesshash.

Monday, April 8, 2013

googla analytics api call details

https://developers.google.com/analytics/resources/articles/gdataCommonQueries 
http://ga-dev-tools.appspot.com/explorer/ 

Site referrals

$ga = $this->service->data_ga->get(
    "ga:34343434",
    $startDate,
    $endDate,
    "ga:visits",
    array(
        "dimensions" => "ga:source",
        'sort' => '-ga:visits',
        'segment' => 'gaid::-8'
    )
);
Search referrals

 $ga = $this->service->data_ga->get(
                $this->accountId,
                $this->startDate,
                $this->endDate,
                "ga:visits",
                array(
                    "dimensions" => "ga:keyword",
                    'sort' => '-ga:visits',
                    "filters" => "ga:medium==organic"
                )
            );
It would seem
ga:medium
ge:visits
does the trick,
  • (none) is "direct traffic
  • organic + cpc is search engine
  • referral is non search engine link
then, the sum of everything else is "campaign"

Keywords from Search Engines

$ga = $this->service->data_ga->get(
    $this->accountId,
    $this->startDate,
    $this->endDate,
    "ga:visits",
    array(
        "dimensions" => "ga:keyword",
        'sort' => '-ga:visits'
    )
);
$ga = $this->service->data_ga->get(
    $this->accountId,
    $this->startDate,
    $this->endDate,
    "ga:visits",
    array(
        "dimensions" => "ga:keyword",
        'sort' => '-ga:visits',
        "filters" => "ga:medium==organic"
    )
);

Search Engines

$ga = $this->service->data_ga->get(
    $this->accountId,
    $this->startDate,
    $this->endDate,
    "ga:visits",
    array(
        "dimensions" => "ga:source",
        'sort' => '-ga:visits',
        "filters" => "ga:medium==cpa,ga:medium==cpc,ga:medium==cpm,ga:medium==cpp,ga:medium==cpv,ga:medium==organic,ga:medium==ppc"
    )
);
Top Landing Pages

$ga = $this->service->data_ga->get(
    $this->accountId,
    $this->startDate,
    $this->endDate,
    "ga:visits",
    array(
        "dimensions" => "ga:landingPagePath",
        'sort' => '-ga:visits'
    )
);
Search referrer details

$ga = $this->service->data_ga->get(
$this->accountId,
$this->startDate,
$this->endDate,
"ga:visits,ga:bounces,ga:visitors,ga:newVisits,ga:timeOnSite,ga:entrances,ga:pageviews,ga:timeOnPage,ga:exits",
array(
"dimensions" => "ga:referralPath",
'sort' => '-ga:visits',
'segment' => 'gaid::-8',
"filters" => "ga:source==".urlencode($referrer)
)
);



 Get segments list

$segments = $analytics->management_segments->listManagementSegments();
Google_Segments Object
(
    [username] => 623644681999-dmg2maloc8obsuiiru0k0fv8no0bouv2@developer.gserviceaccount.com
    [kind] => analytics#segments
    [__itemsType:protected] => Google_Segment
    [__itemsDataType:protected] => array
    [items] => Array
        (
            [0] => Google_Segment Object
                (
                    [definition] => 
                    [kind] => analytics#segment
                    [segmentId] => gaid::-1
                    [created] => 
                    [updated] => 
                    [id] => -1
                    [selfLink] => https://www.googleapis.com/analytics/v3/management/segments/gaid::-1
                    [name] => All Visits
                )

            [1] => Google_Segment Object
                (
                    [definition] => ga:visitorType==New Visitor
                    [kind] => analytics#segment
                    [segmentId] => gaid::-2
                    [created] => 
                    [updated] => 
                    [id] => -2
                    [selfLink] => https://www.googleapis.com/analytics/v3/management/segments/gaid::-2
                    [name] => New Visitors
                )

            [2] => Google_Segment Object
                (
                    [definition] => ga:visitorType==Returning Visitor
                    [kind] => analytics#segment
                    [segmentId] => gaid::-3
                    [created] => 
                    [updated] => 
                    [id] => -3
                    [selfLink] => https://www.googleapis.com/analytics/v3/management/segments/gaid::-3
                    [name] => Returning Visitors
                )

            [3] => Google_Segment Object
                (
                    [definition] => ga:medium==cpa,ga:medium==cpc,ga:medium==cpm,ga:medium==cpp,ga:medium==cpv,ga:medium==ppc
                    [kind] => analytics#segment
                    [segmentId] => gaid::-4
                    [created] => 
                    [updated] => 
                    [id] => -4
                    [selfLink] => https://www.googleapis.com/analytics/v3/management/segments/gaid::-4
                    [name] => Paid Search Traffic
                )

            [4] => Google_Segment Object
                (
                    [definition] => ga:medium==organic
                    [kind] => analytics#segment
                    [segmentId] => gaid::-5
                    [created] => 
                    [updated] => 
                    [id] => -5
                    [selfLink] => https://www.googleapis.com/analytics/v3/management/segments/gaid::-5
                    [name] => Non-paid Search Traffic
                )

            [5] => Google_Segment Object
                (
                    [definition] => ga:medium==cpa,ga:medium==cpc,ga:medium==cpm,ga:medium==cpp,ga:medium==cpv,ga:medium==organic,ga:medium==ppc
                    [kind] => analytics#segment
                    [segmentId] => gaid::-6
                    [created] => 
                    [updated] => 
                    [id] => -6
                    [selfLink] => https://www.googleapis.com/analytics/v3/management/segments/gaid::-6
                    [name] => Search Traffic
                )

            [6] => Google_Segment Object
                (
                    [definition] => ga:medium==(none)
                    [kind] => analytics#segment
                    [segmentId] => gaid::-7
                    [created] => 
                    [updated] => 
                    [id] => -7
                    [selfLink] => https://www.googleapis.com/analytics/v3/management/segments/gaid::-7
                    [name] => Direct Traffic
                )

            [7] => Google_Segment Object
                (
                    [definition] => ga:medium==referral
                    [kind] => analytics#segment
                    [segmentId] => gaid::-8
                    [created] => 
                    [updated] => 
                    [id] => -8
                    [selfLink] => https://www.googleapis.com/analytics/v3/management/segments/gaid::-8
                    [name] => Referral Traffic
                )

            [8] => Google_Segment Object
                (
                    [definition] => ga:goalCompletionsAll>0
                    [kind] => analytics#segment
                    [segmentId] => gaid::-9
                    [created] => 
                    [updated] => 
                    [id] => -9
                    [selfLink] => https://www.googleapis.com/analytics/v3/management/segments/gaid::-9
                    [name] => Visits with Conversions
                )

            [9] => Google_Segment Object
                (
                    [definition] => ga:transactions>0
                    [kind] => analytics#segment
                    [segmentId] => gaid::-10
                    [created] => 
                    [updated] => 
                    [id] => -10
                    [selfLink] => https://www.googleapis.com/analytics/v3/management/segments/gaid::-10
                    [name] => Visits with Transactions
                )

            [10] => Google_Segment Object
                (
                    [definition] => ga:isMobile==Yes
                    [kind] => analytics#segment
                    [segmentId] => gaid::-11
                    [created] => 
                    [updated] => 
                    [id] => -11
                    [selfLink] => https://www.googleapis.com/analytics/v3/management/segments/gaid::-11
                    [name] => Mobile Traffic
                )

            [11] => Google_Segment Object
                (
                    [definition] => ga:bounces==0
                    [kind] => analytics#segment
                    [segmentId] => gaid::-12
                    [created] => 
                    [updated] => 
                    [id] => -12
                    [selfLink] => https://www.googleapis.com/analytics/v3/management/segments/gaid::-12
                    [name] => Non-bounce Visits
                )

            [12] => Google_Segment Object
                (
                    [definition] => ga:isTablet==Yes
                    [kind] => analytics#segment
                    [segmentId] => gaid::-13
                    [created] => 
                    [updated] => 
                    [id] => -13
                    [selfLink] => https://www.googleapis.com/analytics/v3/management/segments/gaid::-13
                    [name] => Tablet traffic
                )

        )

    [itemsPerPage] => 1000
    [previousLink] => 
    [startIndex] => 1
    [nextLink] => 
    [totalResults] => 13
)

google api chart tools Visualization

https://developers.google.com/chart/interactive/docs/gallery/areachart

<!doctype html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
        google.load("visualization", "1", {packages: ["corechart"]});
        jQuery(document).ready(function () {
            google.setOnLoadCallback(drawGraph);
            function drawGraph() {
                var data = google.visualization.arrayToDataTable([
                    ['Month', 'Pritom', 'Samir', 'Raju', 'Sanjoy', 'Kamol'],
                    ['2004/05', 165,      938,     522,     998,     450],
                    ['2005/06', 135,      1120,    599,     1268,    288],
                    ['2006/07', 157,      1167,    587,     807,     397],
                    ['2007/08', 139,      1110,    615,     968,     215],
                    ['2008/09', 136,      691,     629,     1026,    366]
                ]);

                // Create and draw the visualization.
                var ac = new google.visualization.AreaChart(document.getElementById('visualization'));
                ac.draw(data, {
                    title: 'Monthly Point Distribution',
                    isStacked: true,
                    width: 600,
                    height: 400,
                    vAxis: {title: "Point"},
                    hAxis: {title: "Month"}
                });
            }
        });
    </script>
</head>
<body>
<div id='visualization'></div>
</body>
</html>


And output will be like this:

Sunday, April 7, 2013

Google APIs Console and service account setup

Google php library

https://code.google.com/p/google-api-php-client/wiki/OAuth2

https://docs.google.com/file/d/0B5nZNPW48dpFMTA5OU1SbUNkMW8/edit?usp=sharing

Overview

OAuth 2.0 is an emerging standard for accessing protected resources on the web. The Google APIs and the google-api-php-client library support OAuth 2.0.

Further Reading

Overview

Use OAuth 2.0 to access to protected data through the Google APIs. Google APIs support a variety of flows designed to support different types of client applications. With all of these flows the client application requests an access token that is associated with only your client application and the owner of the protected data being accessed. The access token is also associated with a limited scope that define the kind of data the your client application has access to (for example "Manage your tasks"). An important goal for OAuth 2.0 is to provide secure and convenient access to the protected data, while minimizing the potential impact if an access token is stolen.

Google APIs Console

Before you can use OAuth 2.0, you must register your application using the Google APIs Console.
Visit the Google API Console to generate your developer key, OAuth2 client id, OAuth2 client secret, and register your OAuth2 redirect uri. Copy their values since your will need to input them in your application.
  • From the "Services" screen, activate access to the API you want to use.
  • Click on "API Access" in the left column
  • Click the button labeled "Create an OAuth2 client ID"
  • Give your application a name and click "Next"
  • Select your "Application type"
  • Click "Create client ID"
  • Click "Edit..." for your new client ID
  • Under the callback URL, enter the fully qualified URL for your PHP application (example http://localhost/googleplus/index.php).

Web Application

Now that you've registered your application with the Google APIs Console, you can now create a web application that uses OAuth 2.0. Here is an example demonstrating how to do authentication with OAuth 2.0 in a web application. The full code for this sample is in the repository.
<?php
require_once 'path/to/Google_Client.php';

$client = new Google_Client();
$client->setClientId('insert_your_oauth2_client_id');
$client->setClientSecret('insert_your_oauth2_client_secret');
$client->setRedirectUri('insert_your_oauth2_redirect_uri');
$client->setDeveloperKey('insert_your_developer_key');
If the user has been redirected back to our page with an authorization code, exchange the code for an access token.
if (isset($_GET['code'])) {
  $client->authenticate();
  $_SESSION['token'] = $client->getAccessToken();
  header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}

Service Accounts

Service Accounts provide certificate-based authentication for server-to-server interactions. This means, for example, that a request from a web application to Google Cloud Storage can be authenticated via a certificate instead of a shared key. Certificates offer better security properties than shared keys and passwords, largely because they are not human-readable or guessable.
Warning: Very few Google APIs currently support Service Accounts. Service accounts are currently supported by the following Google developer services:
  • Google Cloud Storage
  • Google Prediction API
  • Google URL Shortener
  • Google OAuth 2.0 Authorization Server
  • Google BigQuery
To get started:
  1. Visit https://code.google.com/apis/console
  2. Press the down arrow in the left panel (under the Google apis logo).
  3. Press create.
  4. Name your project "Prediction Test Project".
  5. Press create project.
  6. Now a list of APIs should appear. You want to find "Prediction API" and switch that API to "ON".
  7. Select the API Access tab on the left side.
  8. Press "Create OAuth 2.0 Client" and create your client.
  9. Select Service Account as the application type.
  10. Press Download private key.
Now open the examples /prediction/serviceAccount.php sample application in your editor.
  • Make sure you have a recent version of the Google APIs PHP Client downloaded from here.
  • Replace CLIENT_ID with your newly generated clientId. It should look like:
  • xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com
  • Replace SERVICE_ACCOUNT_NAME with the email address. It should look like:
  • xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@developer.gserviceaccount.com
  • Replace KEY_FILE with the path to your private key. Make sure it is saved in a safe place, and readable the sample app.
// Set your client id, service account name, and the path to your private key.
// For more information about obtaining these keys, visit:
// https://developers.google.com/console/help/#service_accounts
const CLIENT_ID = 'insert_your_client_id';
const SERVICE_ACCOUNT_NAME = 'insert_your_service_account_name';
// Make sure you keep your key.p12 file in a secure location, and isn't
// readable by others.
const KEY_FILE = '/super/secret/path/to/key.p12';
// Load the key in PKCS 12 format (you need to download this from the
// Google API Console when the service account was created.
$client = new Google_Client();
...
$key = file_get_contents(KEY_FILE);
$client->setClientId(CLIENT_ID);
$client->setAssertionCredentials(new Google_AssertionCredentials(
  SERVICE_ACCOUNT_NAME,
  array('https://www.googleapis.com/auth/prediction'),
  $key)
);
There is a full sample of using the Prediction API with a Service account.
Learn more about Service accounts from the announcement.


Solving invalid_grant errors

Make sure your server's clock is in sync with NTP.


Here is the URL:
The value which you are referencing is:  54774085
And this is also the value I see in the admin area for "Profile ID"  (54774085)

I had used Service Account for Google Analytics, and get token and get data from google analytics in ruby. It's work for me.
You can try to setup Google Analytics to work with your newly created Service Account:
        -Open Admin section of Google Analytics
        -Click on Users and create a new user in Analytics with the e-mail address provided by the Google API Service Account I had done state above. and i resolve error 403.