Core Reporting API - Reference Guide - Google Developers
文章推薦指數: 80 %
Authorization: Bearer {oauth2-token} GET https://www.googleapis.com/analytics/v3/data/ga ?ids=ga:12345 &start-date=2008-10-01 ... Google Analytics Reporting CoreReportingAPI Language English BahasaIndonesia Deutsch Español Français Português–Brasil Русский 中文–简体 日本語 한국어 Signin Guides Reference Support Google Analytics Reporting CoreReportingAPI Guides Reference Support APIReference StandardQueryParameters ErrorResponses Home Products GoogleAnalytics Reporting CoreReportingAPI Reference CoreReportingAPI-ReferenceGuide Thisdocumentprovidesthecompletereferenceforbothqueryandresponsefor theCoreReportingAPIversion3.0. Thereisanupdatedversionofthe GoogleAnalyticsReportingAPI. Werecommend migrating yourcodetodaytotakeadvantageofthenewAPI's keyfeatures. Introduction YouquerytheCoreReportingAPIforGoogleAnalyticsreportdata.Eachqueryrequiresa view(profile)ID,astartandenddate,andatleastonemetric.Youmayalsosupplyadditional queryparameterssuchasdimensions,filters,andsegmentstorefineyourquery.Seethe OverviewGuide tounderstandhowalltheseconceptsworktogether. Request TheAPIprovidesasinglemethodtorequestdata: analytics.data.ga.get() Thismethodisexposedinvarious clientlibraries andhaslanguagespecificinterfacestosetthequeryparameters. TheAPIalsocanbequeriedasaREST-fulendpoint: Authorization:Bearer{oauth2-token} GEThttps://www.googleapis.com/analytics/v3/data/ga ?ids=ga:12345 &start-date=2008-10-01 &end-date=2008-10-31 &metrics=ga:sessions,ga:bounces EachURLqueryparameterspecifiesanAPIqueryparameterthatmustbeURLencoded. QueryParametersSummary Thefollowingtablesummarizesallthequeryparametersacceptedbythe CorereportingAPI.Clickeachparameternameforadetaileddescription. Name Value Required Summary ids string yes TheuniquetableIDoftheform ga:XXXX,whereXXXXistheAnalyticsview(profile)IDforwhichthe querywillretrievethedata. start-date string yes StartdateforfetchingAnalyticsdata.Requestscanspecifyastart dateformattedasYYYY-MM-DD,orasarelativedate (e.g.,today,yesterday,or NdaysAgowhereNisapositiveinteger). end-date string yes EnddateforfetchingAnalyticsdata.Requestcanspecifyanenddate formattedasYYYY-MM-DD,orasarelativedate(e.g., today,yesterday,orNdaysAgo whereNisapositiveinteger). metrics string yes Alistofcomma-separatedmetrics,suchasga:sessions,ga:bounces. dimensions string no Alistofcomma-separateddimensionsforyourAnalyticsdata,suchas ga:browser,ga:city. sort string no Alistofcomma-separated dimensionsandmetricsindicatingthesortingorderand sortingdirectionforthereturneddata. filters string no Dimensionormetricfiltersthat restrictthedatareturnedforyourrequest. segment string no Segmentsthedatareturnedfor yourrequest. samplingLevel string no Thedesiredsamplinglevel.AllowedValues: DEFAULT—Returnsresponsewithasamplesize thatbalancesspeedandaccuracy. FASTER—Returnsafastresponsewithasmaller samplesize. HIGHER_PRECISION—Returnsamoreaccurate responseusingalargesamplesize,butthismayresultinthe responsebeingslower. include-empty-rows boolean no Defaultstotrue;ifsettofalse,rowswhereallmetricvaluesare zerowillbeomittedfromtheresponse. start-index integer no Thefirstrowofdatatoretrieve, startingat1.Usethisparameterasapaginationmechanism alongwiththemax-resultsparameter. max-results integer no Themaximumnumberofrowsto includeintheresponse. output string no ThedesiredoutputtypefortheAnalyticsdatareturnedintheresponse. Acceptablevaluesarejsonand dataTable.Default:json. fields string no Selectorspecifyingasubsetoffieldstoincludeintheresponse. prettyPrint string no Returnsresponsewithindentationsandlinebreaks.Defaultfalse. userIp string no SpecifiesIPaddressoftheenduserforwhomtheAPIcallisbeingmade. Usedto capusageperIP. quotaUser string no AlternativetouserIpincaseswhentheuser'sIPaddressisunknown. access_token string no Onepossiblewaytoprovidean OAuth2.0token. callback string no NameoftheJavaScriptcallbackfunctionthathandlestheresponse.Usedin JavaScriptJSON-Prequests. key string no UsedforOAuth1.0aauthorizationtospecifyyourapplicationtogetquota.Forexample: key=AldefliuhSFADSfasdfasdfASdf. QueryParameterDetails ids ids=ga:12345 Required. TheuniqueIDusedtoretrievetheAnalyticsdata.ThisID istheconcatenationofthenamespacega:withthe Analyticsview(profile)ID.Youcanretrievetheview(profile)IDbyusing theanalytics.management.profiles.list method,whichprovidestheidintheView(Profile)resource inthe Google AnalyticsManagementAPI. start-date start-date=2009-04-20 Required. AllAnalyticsdatarequestsmustspecifyadaterange. Ifyoudonotincludestart-date andend-dateparametersintherequest,theserverreturns anerror.Datevaluescanbeforaspecificdatebyusingthepattern YYYY-MM-DDorrelativebyusingtoday, yesterday,ortheNdaysAgopattern. Valuesmustmatch [0-9]{4}-[0-9]{2}-[0-9]{2}|today|yesterday|[0-9]+(daysAgo). Theearliestvalidstart-dateis2005-01-01. Thereisnoupperlimitrestrictionforastart-date. Relativedatesarealwaysrelativetothecurrentdateatthetimeofthe queryandarebasedonthetimezoneoftheview(profile)specifiedinthe query. Exampledaterangeforthelast7days(startingyesterday)usingrelative dates: &start-date=7daysAgo &end-date=yesterday end-date end-date=2009-05-20 Required. AllAnalyticsdatarequestsmustspecifyadaterange. Ifyoudonotincludestart-date andend-dateparametersintherequest,theserverreturns anerror.Datevaluescanbeforaspecificdatebyusingthepattern YYYY-MM-DDorrelativebyusingtoday, yesterday,ortheNdaysAgopattern. Valuesmustmatch [0-9]{4}-[0-9]{2}-[0-9]{2}|today|yesterday|[0-9]+(daysAgo). Theearliestvalidend-dateis 2005-01-01.Thereisnoupperlimitrestrictionfor anend-date. Relativedatesarealwaysrelativetothecurrentdateatthetimeofthe queryandarebasedonthetimezoneoftheview(profile)specifiedinthe query. Exampledaterangeforthelast10days(startingtoday)usingrelative dates: &start-date=9daysAgo &end-date=today dimensions dimensions=ga:browser,ga:city Optional. Thedimensionsparameterbreaksdownmetricsbycommoncriteria; forexample,byga:browserorga:city. Whileyoucanask forthetotalnumberofpageviewstoyoursite,itmightbemore interestingtoaskforthenumberofpageviewsbrokendownby browser.Inthiscase,you'llseethenumberofpageviewsfrom Firefox,InternetExplorer,Chrome,andsoforth. Whenusingdimensionsinadatarequest,beaware ofthefollowingconstraints: Youcansupplyamaximumof7dimensionsinanyquery. Youcannotsendaquerycomposedonlyof dimensions:youmustcombineanyrequesteddimensionswithat leastonemetric. Onlycertaindimensionscanbequeriedinthesamequery.Usethe validcombinationtoolinthe DimensionsandMetricsReferencetoseewhichdimensions canbeusedtogether. metrics metrics=ga:sessions,ga:bounces Required. Theaggregatedstatisticsforuseractivitytoyoursite,suchas clicksorpageviews. Ifaqueryhasnodimensionsparameter,thereturned metricsprovideaggregatevaluesfortherequesteddaterange, suchasoverallpageviewsortotalbounces.However,when dimensionsarerequested,valuesaresegmentedbydimension value.Forexample,ga:pageviewsrequestedwith ga:countryreturnsthetotalpageviewspercountry. Whenrequestingmetrics,keepinmind: Anyrequestmustsupplyatleastonemetric;arequestcannot consistonlyofdimensions. Youcansupplyamaximumof10metricsforanyquery. Mostcombinationsofmetricsfrommultiplecategoriescanbe usedtogether,providednodimensionsarespecified. Ametriccanbeusedincombinationwithotherdimensionsor metrics,butonlywherevalidcombinationsapplyforthatmetric. Seethe Dimensions andMetricsReferencefordetails. sort sort=ga:country,ga:browser Optional. Alistofmetricsanddimensionsindicatingthesortingorderand sortingdirectionforthereturneddata. Sortingorderisspecifiedbythelefttoright orderofthemetricsanddimensionslisted. Sortingdirectiondefaultstoascendingandcanbe changedtodescendingbyusingaminussign(-) prefixontherequestedfield. Sortingtheresultsofaqueryenablesyoutoaskdifferent questionsaboutyourdata.Forexample,toaddressthequestion "Whataremytopcountries,andwhichbrowsersdotheyusemost?" youcanmakeaquerywiththefollowingparameter.Itsorts firstby ga:countryandthenbyga:browser,bothin ascendingorder: sort=ga:country,ga:browser Toanswertherelatedquestion"Whataremytopbrowsers,and whichcountriesusethemmost?",youcanmakeaquerywiththe followingparameter.Itsortsfirstbyga:browserand thenbyga:country,bothinascendingorder: sort=ga:browser,ga:country Whenusingthesortparameter,keepinmindthe following: Sortonlybydimensionsormetricsvaluesthatyouhaveused inthedimensionsormetrics parameters.Ifyourrequestsortsonafieldthatisnot indicatedineitherthedimensionsormetricsparameter,you willreceiveaerror. Bydefault,stringsaresortedinascendingalphabeticalorder inen-USlocale. Numbersaresortedinascendingnumericorderbydefault. Datesaresortedinascendingorderbydatebydefault. filters filters=ga:medium%3D%3Dreferral FilterSyntax FilterOperators FilterExpressions CombiningFilters ORoperator ANDoperator Optional. Thefiltersquerystringparameterrestrictsthe datareturnedfromyourrequest.Tousethefilters parameter,supplyadimensionormetriconwhichtofilter,followed bythefilterexpression.Forexample,thefollowingquery requestsga:pageviewsandga:browserfor view(profile)12134,wherethega:browser dimensionstartswiththestringFirefox: https://www.googleapis.com/analytics/v3/data/ga ?ids=ga:12134 &dimensions=ga:browser &metrics=ga:pageviews &filters=ga:browser%3D~%5EFirefox &start-date=2007-01-01 &end-date=2007-12-31 Filteredqueriesrestricttherowsthatdo(ordonot)getincludedintheresult.Eachrowintheresultistestedagainstthefilter:ifthefiltermatches,therowisretainedandifitdoesn'tmatch,therowisdropped. URLEncoding:TheGoogleAPIclientlibrariesautomaticallyencode thefilteroperators. Dimensionfiltering:Filteringoccursbeforeanydimensionsareaggregated,sothatthereturnedmetricsrepresentthetotalforonlytherelevantdimensions.Intheexampleabove,thenumberofpageviewswouldbeonlythosepageviewswhereFirefoxisthebrowser. Metricsfiltering:Filteringonmetricsoccursafterthemetricsareaggregated. Validcombinations:Youcanfilterfora dimensionormetricthatisnotpartofyourquery,providedall dimensions/metricsintherequestandthefilterare validcombinations.Forexample,youmightwanttoqueryfora datedlistofpageviews,filteringonaparticularbrowser.See the Dimensions andMetricsReferenceformoreinformation. FilterSyntax Asinglefilterusestheform: ga:nameoperatorexpression Inthissyntax: name—thenameofthedimensionormetrictofilteron.Forexample:ga:pageviewsfiltersonthepageviewsmetric. operator—definesthetypeoffiltermatchtouse.Operatorsarespecifictoeitherdimensionsormetrics. expression—statesthevaluestobeincludedinorexcludedfromtheresults.Expressionsuseregularexpressionsyntax. FilterOperators Therearesixfilteroperatorsfordimensionsandsixfilteroperatorsfor metrics.TheoperatorsmustbeURL-encodedinordertobeincluded inURLquerystrings. Tip:Usethe DataFeed QueryExplorertodesignfiltersthatneedURLencoding, sincetheQueryExplorerautomaticallyencodesURLScontaining stringsandspaces. MetricFilters Operator Description URLEncodedForm Examples == Equals %3D%3D Returnresultswherethetimeonthepageisexactlytenseconds: filters=ga:timeOnPage%3D%3D10 != Doesnotequal !%3D Returnresultswherethetimeonthepageisnottenseconds: filters=ga:timeOnPage!%3D10 > Greaterthan %3E Returnresultswherethetimeonthepageisstrictlygreaterthantenseconds: filters=ga:timeOnPage%3E10 < Lessthan %3C Returnresultswherethetimeonthepageisstrictlylessthantenseconds: filters=ga:timeOnPage%3C10 >= Greaterthanorequalto %3E%3D Returnresultswherethetimeonthepageistensecondsormore: filters=ga:timeOnPage%3E%3D10 <= Lessthanorequalto %3C%3D Returnresultswherethetimeonthepageistensecondsorless: filters=ga:timeOnPage%3C%3D10 DimensionFilters Operator Description URLEncodedForm Example == Exactmatch %3D%3D AggregatemetricswherethecityisIrvine: filters=ga:city%3D%3DIrvine != Doesnotmatch !%3D AggregatemetricswherethecityisnotIrvine: filters=ga:city!%3DIrvine =@ Containssubstring %3D@ AggregatemetricswherethecitycontainsYork: filters=ga:city%3D@York !@ Doesnotcontainsubstring !@ AggregatemetricswherethecitydoesnotcontainYork: filters=ga:city!@York =~ Containsamatchfortheregularexpression %3D~ AggregatemetricswherethecitystartswithNew: filters=ga:city%3D~%5ENew.* (%5EistheURLencodedfromofthe^characterthatanchorsapatterntothebeginningofthestring.) !~ Doesnotmatchregularexpression !~ AggregatemetricswherethecitydoesnotstartwithNew: filters=ga:city!~%5ENew.* FilterExpressions Thereareacoupleofimportantrulesforfilterexpressions: URL-reservedcharacters—Characterssuchas&mustbeurl-encodedintheusualway. Reservedcharacters—Thesemicolonandcommamustbebackslashescapedwhentheyappearinanexpression: semicolon\; comma\, RegularExpressions—Youcanalsouseregularexpressionsinfilterexpressions usingthe=~and!~operators.TheirsyntaxissimilartoPerlregularexpressions andhavetheseadditionalrules: Maximumlengthof128characters—Regularexpressions longerthan128charactersresultina400BadRequeststatus codereturnedfromtheserver. Casesensitivity—Regularexpressionmatchingiscase-insensitive. CombiningFilters FilterscanbecombinedusingORandANDbooleanlogic.This allowsyoutoeffectivelyextendthe128characterlimitofafilterexpression. OR TheORoperatorisdefinedusingacomma(,). IttakesprecedenceovertheANDoperatorandmayNOTbeused tocombinedimensionsandmetricsinthesameexpression. Examples:(eachmustbeURLencoded) Countryiseither(UnitedStatesORCanada): ga:country==United%20States,ga:country==Canada Firefoxuserson(WindowsORMacintosh)operatingsystems: ga:browser==Firefox;ga:operatingSystem==Windows,ga:operatingSystem==Macintosh AND TheANDoperatorisdefinedusingasemi-colon(;). ItisprecededbytheORoperatorandCANbeusedtocombine dimensionsandmetricsinthesameexpression. Examples:(eachmustbeURLencoded) CountryisUnitedStatesANDthebrowserisFirefox: ga:country==United%20States;ga:browser==Firefox CountryisUnitedStatesANDlanguagedoesnotstartwith'en': ga:country==United%20States;ga:language!~^en.* Operatingsystemis(WindowsORMacintosh)ANDbrowseris(FirefoxORChrome): ga:operatingSystem==Windows,ga:operatingSystem==Macintosh;ga:browser==Firefox,ga:browser==Chrome CountryisUnitedStatesANDsessionsaregreaterthan5: ga:country==United%20States;ga:sessions>5 segment segment=gaid::-10 segment=sessions::condition::ga:medium%3D%3Dreferral segment=users::condition::ga:browser%3D%3DChrome Optional. ForcompletedetailsonhowtorequestasegmentintheCoreReportingAPI seetheSegments DevGuide. Foraconceptualoverviewofsegments,seethe SegmentsFeatureReference and SegmentsintheHelpCenter. DimensionsandMetricsallowedin segments. Notalldimensionsandmetricscanbeusedinsegments.Toreview whichdimensionsandmetricsareallowedinsegmentsvisitthe DimensionsandMetricsExplorer. Note:Thedynamic:: prefixhasbeendeprecatedasofMarch27,2014.Itisrecommendedthatyou migratetothenewsyntaxassoonaspossible. samplingLevel samplingLevel=DEFAULT Optional. Usethisparametertosetthesamplinglevel(i.e.thenumberofsessions usedtocalculatetheresult)forareportingquery.Theallowedvaluesare consistentwiththewebinterfaceandinclude: DEFAULT—Returnsresponsewithasamplesize thatbalancesspeedandaccuracy. FASTER—Returnsafastresponsewithasmaller samplesize. HIGHER_PRECISION—Returnsamoreaccurate responseusingalargesamplesize,butthismayresultinthe responsebeingslower. Ifnotsupplied,theDEFAULTsamplinglevelwillbe used. SeetheSamplingsectionfordetailsonhowto calculatethepercentageofsessionsthatwereusedforaquery. include-empty-rows include-empty-rows=true Optional. Defaultstotrue;ifsettofalse,rowswhereallmetricvaluesare zerowillbeomittedfromtheresponse.Forexampleifyouinclude morethanonemetricinaquery,therowsareonlyremovedifallmetric valuesarezero.Thiscanbeusefulwhen makingarequestwhereitisexpectedthatthenumberofvalidrows ismuchsmallerthenthenumberofexpecteddimensionvalues. start-index start-index=10 Optional. Ifnotsupplied,thestartingindexis1.(Result indexesare1-based.Thatis,thefirstrowisrow 1,notrow0.)Usethisparameter asapaginationmechanismalongwiththemax-results parameterforsituationswhentotalResultsexceeds 10,000andyouwanttoretrieverowsindexedat10,001and beyond. max-results max-results=100 Optional. Maximumnumberofrowstoincludeinthisresponse.Youcan usethisincombinationwithstart-indextoretrievea subsetofelements,oruseitalonetorestrictthenumberof returnedelements,startingwiththefirst. Ifmax-resultsisnotsupplied,thequeryreturnsthe defaultmaximumof1000rows. TheAnalyticsCoreReportingAPIreturnsamaximumof10,000rows perrequest,nomatterhowmanyyouaskfor.Itcanalsoreturn fewerrowsthanrequested,iftherearen'tasmanydimension segmentsasyouexpect.Forinstance,therearefewerthan300 possiblevaluesforga:country,sowhensegmentingonly bycountry,youcan'tgetmorethan300rows,evenifyou setmax-resultstoahighervalue. output output=dataTable Optional. UsethisparametertosettheoutputtypeoftheAnalyticsdatareturned inthe response.Theallowedvaluesare: json—Outputsthedefaultrows propertyintheresponse,containingaJSONobject. dataTable—OutputsadataTable propertyintheresponse,containinga DataTableobject.ThisDataTableobjectcanbeused directlywithGoogleChartsvisualizations. Ifnotsupplied,thedefaultJSONresponsewillbeused. fields fields=rows,columnHeaders(name,dataType) Optional. Specifieswhichfieldstoreturninapartialresponse.Ifyouonly useasubsetofthefieldsintheAPIresponse,youcanusethe fieldsparametertospecifywhichfieldstoinclude. Theformatofthefieldsrequestparametervalueislooselybasedon XPathsyntax.Thesupportedsyntaxissummarizedbelow. Useacomma-separatedlisttoselectmultiplefields. Usea/btoselectafieldbthatisnestedwithinfielda; usea/b/ctoselectafieldcnestedwithinb. Useasub-selectortorequestasetofspecificsub-fieldsofarrays orobjectsbyplacingexpressionsinparentheses"()". Forexample:fields=columnHeaders(name,dataType)returns onlythenameanddataTypefieldsinthe columnHeadersarray. Youcanalsospecifyasinglesub-field,where fields=columnHeader(name)isequivalentto fields=columnHeader/name. prettyPrint prettyPrint=false Optional. Returnstheresponseinahuman-readableformatiftrue. Defaultvalue:false. quotaUser quotaUser=4kh4r2h4 Optional. Letsyou enforceper-userquotasfromaserver-sideapplicationevenincases whentheuser'sIPaddressisunknown.Thiscanoccur,forexample,with applicationsthatruncronjobsonAppEngineonauser'sbehalf.Youcan chooseanyarbitrarystringthatuniquelyidentifiesauser,butitis limitedto40characters. ThisoverridesuserIpifbothareprovided. Response Ifsuccessful,thisrequestreturnsaresponsebodywiththeJSON structuredefinedbelow.Iftheoutput parameterissettodataTablethentherequestreturns aresponsebodywiththeJSON(DataTable)structuredefinedbelow. Note:theterm"results"refersto theentiresetofrowsthatmatchthequery,while"response"refers tothesetofrowsreturnedonthecurrentpageofresults.They canbedifferentifthetotalnumberresultsisgreaterthanthe pagesizeforthecurrentresponse,asexplainedin itemsPerPage. { "kind":"analytics#gaData", "id":string, "selfLink":string, "containsSampledData":boolean, "query":{ "start-date":string, "end-date":string, "ids":string, "dimensions":[ string ], "metrics":[ string ], "include-empty-rows":boolean "samplingLevel":string, "sort":[ string ], "filters":string, "segment":string, "start-index":integer, "max-results":integer }, "itemsPerPage":integer, "totalResults":integer, "previousLink":string, "nextLink":string, "profileInfo":{ "profileId":string, "accountId":string, "webPropertyId":string, "internalWebPropertyId":string, "profileName":string, "tableId":string }, "columnHeaders":[ { "name":string, "columnType":string, "dataType":string } ], "rows":[ [ string ] ], "sampleSize":string, "sampleSpace":string, "totalsForAllResults":[ { metricName:string, ... } ] } ResponseFields Thepropertiesoftheresponsebodystructurearedefinedasfollows: PropertyName Value Description kind string Resourcetype.Valueis"analytics#gaData". id string AnIDforthisdataresponse. query object Thisobjectcontainsallthevaluespassedasparameters tothequery.Themeaningofeachfieldisexplainedin thedescriptionofitscorresponding queryparameter. query.start-date string Startdate. query.end-date string Enddate. query.ids string UniquetableID. query.dimensions[] list Listofanalyticsdimensions. query.metrics[] list Listofanalyticsmetrics. query.samplingLevel string Requestedsamplinglevel. query.include-empty-rows boolean Defaultstotrue;ifsettofalse,rowswhereallmetric valuesarezerowillbeomittedfromtheresponse. query.sort[] list Listofmetricsordimensionsonwhichthedataissorted. query.filters string Comma-separatedlistofmetricordimensionfilters. query.segment string Analyticssegment. query.start-index integer Startindex. query.max-results integer Maximumresultsperpage. startIndex integer Thestartingindexofrowsspecifiedby thestart-indexqueryparameter.Default valueis1. itemsPerPage integer Themaximumnumberofrowstheresponsecancontain, regardlessoftheactualnumberofrowsreturned.If themax-resultsqueryparameterisspecified, thevalueofitemsPerPageisthesmaller ofmax-resultsor10,000.Thedefaultvalue ofitemsPerPageis1000. totalResults integer Thetotalnumberofrowsinthequeryresult,regardless ofthenumberofrowsreturnedintheresponse.Forqueriesthat resultinalargenumberofrows, totalResultscanbegreaterthan itemsPerPage. SeePagingformoreexplanation oftotalResultsand itemsPerPageforlargequeries. startDate string Startdateforthedataquery,asspecifiedbythe start-dateparameter. endDate string Enddateforthedataquery,asspecifiedbythe end-dateparameter. selfLink string Linktothispageofresultsforthisdataquery. previousLink string Linktopreviouspageofresultsforthisdataquery. nextLink string Linktonextpageofresultsforthisdataquery. profileInfo object Informationabouttheview(profile)forwhichthedata wasrequested.View(Profile)dataisavailablethroughthe GoogleAnalyticsManagementAPI. profileInfo.profileId string View(Profile)ID,suchas1174. profileInfo.accountId string AccountIDtowhichthisview(profile)belongs,suchas 30481. profileInfo.webPropertyId string WebPropertyIDtowhichthisview(profile)belongs,suchasUA-30481-1. profileInfo.internalWebPropertyId string InternalIDforthewebpropertytowhichthisview(profile)belongs,suchasUA-30481-1. profileInfo.profileName string Nameoftheview(profile). profileInfo.tableId string TableIDforview(profile),consistingof"ga:"followedby theview(profile)ID. containsSampledData boolean Trueiftheresponsecontainssampleddata. sampleSize string Thenumberofsamplesusedtocalculatethe sampleddata. sampleSpace string Thetotalsamplingspacesize.Thisindicatesthetotalavailable samplespacesizefromwhichthesamples wereselected. columnHeaders[] list Columnheadersthatlistdimensionnamesfollowedbythe metricnames.Theorderofdimensionsandmetricsissame asthosespecifiedintherequestthrough themetricsanddimensions parameters.Thenumberofheadersisthenumberof dimensions+thenumberofmetrics. columnHeaders[].name string Nameofthedimensionormetric. columnHeaders[].columnType string Columntype.Either"DIMENSION"or"METRIC". columnHeaders[].dataType string Datatype.Dimensioncolumnheadershaveonly STRINGasdatatype.Metriccolumnheaders havedatatypesformetricvaluessuchas INTEGER,PERCENT,TIME, CURRENCY,FLOAT, etc.Seethe metadataAPIresponse forallthepossibledatatypes. totalsForAllResults object Totalvaluesfortherequestedmetricsaskey-value pairsofmetricnamesandvalues.Theorderofthemetric totalsissameasthemetricorderspecifiedinthe request. rows[] list Analyticsdatarows,whereeachrowcontainsalistof dimensionvaluesfollowedbythemetricvalues.Theorder ofdimensionsandmetricsissameasspecifiedinthe request.EachrowhasalistofNfields,whereN=the numberofdimensions+thenumberofmetrics. { "kind":"analytics#gaData", "id":string, "selfLink":string, "containsSampledData":boolean, "query":{ "start-date":string, "end-date":string, "ids":string, "dimensions":[ string ], "metrics":[ string ], "samplingLevel":string, "include-empty-rows":boolean, "sort":[ string ], "filters":string, "segment":string, "start-index":integer, "max-results":integer }, "itemsPerPage":integer, "totalResults":integer, "previousLink":string, "nextLink":string, "profileInfo":{ "profileId":string, "accountId":string, "webPropertyId":string, "internalWebPropertyId":string, "profileName":string, "tableId":string }, "columnHeaders":[ { "name":string, "columnType":string, "dataType":string } ], "dataTable":{ "cols":[ { "id":string, "label":string, "type":string } ], "rows":[ { "c":[ { "v":string } ] } ] }, "sampleSize":string, "sampleSpace":string, "totalsForAllResults":[ { metricName:string, ... } ] } ResponseFields Thepropertiesoftheresponsebodystructurearedefinedasfollows: PropertyName Value Description kind string Resourcetype.Valueis"analytics#gaData". id string AnIDforthisdataresponse. query object Thisobjectcontainsallthevaluespassedasparameters tothequery.Themeaningofeachfieldisexplainedin thedescriptionofitscorresponding queryparameter. query.start-date string Startdate. query.end-date string Enddate. query.ids string UniquetableID. query.dimensions[] list Listofanalyticsdimensions. query.metrics[] list Listofanalyticsmetrics. query.samplingLevel string Requestedsamplinglevel. query.include-empty-rows boolean Defaultstotrue;ifsettofalse,rowswhereallmetric valuesarezerowillbeomittedfromtheresponse. query.sort[] list Listofmetricsordimensionsonwhichthedataissorted. query.filters string Comma-separatedlistofmetricordimensionfilters. query.segment string Analyticssegment. query.start-index integer Startindex. query.max-results integer Maximumresultsperpage. startIndex integer Thestartingindexofrowsspecifiedby thestart-indexqueryparameter.Default valueis1. itemsPerPage integer Themaximumnumberofrowstheresponsecancontain, regardlessoftheactualnumberofrowsreturned.If themax-resultsqueryparameterisspecified, thevalueofitemsPerPageisthesmaller ofmax-resultsor10,000.Thedefaultvalue ofitemsPerPageis1000. totalResults integer Thetotalnumberofrowsinthequeryresult,regardless ofthenumberofrowsreturnedintheresponse.Forqueriesthat resultinalargenumberofrows, totalResultscanbegreaterthan itemsPerPage. SeePagingformoreexplanation oftotalResultsand itemsPerPageforlargequeries. startDate string Startdateforthedataquery,asspecifiedbythe start-dateparameter. endDate string Enddateforthedataquery,asspecifiedbythe end-dateparameter. selfLink string Linktothispageofresultsforthisdataquery. previousLink string Linktopreviouspageofresultsforthisdataquery. nextLink string Linktonextpageofresultsforthisdataquery. profileInfo object Informationabouttheview(profile)forwhichthedata wasrequested.View(Profile)dataisavailablethroughthe GoogleAnalyticsManagementAPI. profileInfo.profileId string View(Profile)ID,suchas1174. profileInfo.accountId string AccountIDtowhichthisview(profile)belongs,suchas 30481. profileInfo.webPropertyId string WebPropertyIDtowhichthisview(profile)belongs,suchasUA-30481-1. profileInfo.internalWebPropertyId string InternalIDforthewebpropertytowhichthisview(profile)belongs,suchasUA-30481-1. profileInfo.profileName string Nameoftheview(profile). profileInfo.tableId string TableIDforview(profile),consistingof"ga:"followedby theview(profile)ID. containsSampledData boolean Trueiftheresponsecontainssampleddata. sampleSize string Thenumberofsamplesusedtocalculatethe sampleddata. sampleSpace string Thetotalsamplingspacesize.Thisindicatesthetotalavailable samplespacesizefromwhichthesamples wereselected. columnHeaders[] list Columnheadersthatlistdimensionnamesfollowedbythe metricnames.Theorderofdimensionsandmetricsissame asthosespecifiedintherequestthrough themetricsanddimensions parameters.Thenumberofheadersisthenumberof dimensions+thenumberofmetrics. columnHeaders[].name string Nameofthedimensionormetric. columnHeaders[].columnType string Columntype.Either"DIMENSION"or"METRIC". columnHeaders[].dataType string Datatype.Dimensioncolumnheadershaveonly STRINGasdatatype.Metriccolumnheaders havedatatypesformetricvaluessuchas INTEGER,PERCENT,TIME, CURRENCY,FLOAT, etc.Seethe metadataAPIresponse forallthepossibledatatypes. totalsForAllResults object Totalvaluesfortherequestedmetricsaskey-value pairsofmetricnamesandvalues.Theorderofthemetric totalsissameasthemetricorderspecifiedinthe request. dataTable object ADataTable objectthatcanbeusedwithGoogleCharts. dataTable.cols[] list Alistofcolumndescriptorsfordimensionsfollowedbymetrics.The orderofdimensionsandmetricsisthesameasthosespecifiedinthe requestthroughthemetricsanddimensions parameters.Thenumberofcolumnsisthenumberofdimensions+the numberofmetrics. dataTable.cols[].id string AnID,whichcanbeusedtorefertoaspecificcolumn(asan alternativetousingcolumnindexes).ThedimensionormetricIdis usedtosetthisvalue. dataTable.cols[].label string Alabelforthecolumn(whichmightbedisplayedbyavisualization). ThedimensionormetricIdisusedtosetthisvalue. dataTable.cols[].type string Thedatatypeforthiscolumn. dataTable.rows[] list AnalyticsdatarowsinDataTableformat,whereeachrowisanobject containingalistofcellvaluesfordimensionsfollowedby metrics.Theorderofdimensionsandmetricsissameasspecifiedinthe request.EachcellhasalistofNfields,whereN=the numberofdimensions+thenumberofmetrics. ErrorCodes TheCoreReportingAPIreturnsa200HTTPstatuscode ifarequestissuccessful.Ifthereanerroroccursduring processingofaquery,theAPIreturnsanerrorcodeanddescription. EachapplicationthatusestheanalyticsAPIneedstoimplementproper errorhandlinglogic.Fordetailsontheerrorcodesandhowtohandle them,readthe ErrorResponsesreferenceguide. TryIt! YoucantryoutqueriestotheCoreReportingAPI. Toseethevalidcombinationsofmetricsanddimensionsina query,entersamplevaluesfortheparametersinthe Query Explorer.Theresultsofthesamplequeryareshownasa tablewithvaluesforallthespecifiedmetricsanddimensions. TomakearequestonlivedataandseetheresponseinJSON format,trytheanalytics.data.ga.getmethodinthe Google DataAPIsExplorer. Sampling GoogleAnalyticscalculatescertaincombinationsofdimensionsand metricsonthefly.Toreturnthedatainareasonabletime,Google Analyticsmayonlyprocessasampleofthedata. Youcanspecifythesamplingleveltouseforarequestbysettingthe samplingLevelparameter. IfaCoreReportingAPIresponsecontainssampleddata,thenthe containsSampledDataresponsefieldwillbetrue. Inaddition,2propertieswillprovideinformationaboutthesamplinglevel forthequery:sampleSizeandsampleSpace. Withthese2valuesyoucancalculatethepercentageofsessionsthatwereused forthequery.Forexample,ifsampleSizeis201,000 andsampleSpaceis220,000thenthereportisbased on(201,000/220,000)*100=91.36%ofsessions. See Sampling forageneraldescriptionofsamplingandhowitisusedinGoogle Analytics. HandlingLargeDataResults Ifyouexpectyourquerytoreturnalargeresultset,usethe guidelinesbelowtohelpyouoptimizeyourAPIquery,avoiderrors, andminimizequotaoverruns. Notethatwesetaperformancebaselinebyallowinga maximumof7dimensionsand10metricsinanyoneAPIrequest. Althoughsomequeriesthatspecifylargenumbersofmetricsand dimensionsmaytakelongertoprocessthanothers,limitingthenumber ofrequestedmetricsmightnotbeenoughtoimprovequeryperformance. Instead,youcanusethefollowingtechniquesforthebestperformance results. ReducingDimensionsperQuery TheAPIallowsspecifyingupto7dimensionsinanyonerequest. Manytimes,GoogleAnalyticsmust calculatetheresultsofthesecomplexqueriesonthefly.Thiscan beespeciallytimeconsumingifthenumberofresultingrowsishigh. Forexample,queryingforkeywords,bycitybyhourmaymatch millionsofrowsofdata.Youcanimproveperformancebyreducingthe numberofrowsGoogleAnalyticsneedstoprocessbylimitingthe numberofdimensionsinyourquery. SplittingtheQuerybyDateRange Insteadofpagingthroughthedate-keyedresultsofonelongdate range,considerformingseparatequeriesforoneweek—oreven oneday—atatime.Ofcourse,foralargedataset,evena requestforasingleday'sdatamightreturnmorethan max-results,inwhichcasepagingcannotbeavoided.But inanycase,ifthenumberofmatchingrowsforyourqueryishigher thanmax-results,breakingapartthedaterangemay decreasethetotaltimetoretrievetheresults.Thisapproachcan improveperformanceinbothsingle-threadedandparallelqueries. Paging Pagingthroughresultscanbeausefulwaytobreaklargeresults setsintomanageablechunks.ThetotalResultsfield tellshowmanymatchingrowsexist,anditemsPerPage givesthemaximumnumberofrowsthatcanbereturnedintheresult. IfthereisahighratiooftotalResults toitemsPerPage,thentheindividualqueriesmightbe takinglongerthannecessary.Ifyouneedonlyalimitednumberof rows,suchasfordisplaypurposes,youmayfinditconvenienttoset anexplicitlimitonresponsesizethroughthe max-resultsparameter.However,ifyourapplication needstoprocessalargesetofresultsinitsentirety,then requestingthemaximumallowedrowsmaybemoreefficient. Usinggzip Aneasyandconvenientwaytoreducethebandwidthneededforeachrequest istoenablegzipcompression.AlthoughthisrequiresadditionalCPUtime touncompresstheresults,thetradeoffwithnetworkcostsusuallymakes itveryworthwhile.Inordertoreceiveagzip-encodedresponseyoumust dotwothings:SetanAccept-Encodingheader,andmodifyyour useragenttocontainthestringgzip. HereisanexampleofproperlyformedHTTPheadersforenabling gzipcompression: Accept-Encoding:gzip User-Agent:myprogram(gzip) Exceptasotherwisenoted,thecontentofthispageislicensedundertheCreativeCommonsAttribution4.0License,andcodesamplesarelicensedundertheApache2.0License.Fordetails,seetheGoogleDevelopersSitePolicies.JavaisaregisteredtrademarkofOracleand/oritsaffiliates. Lastupdated2019-06-11UTC. [{ "type":"thumb-down", "id":"missingTheInformationINeed", "label":"MissingtheinformationIneed" },{ "type":"thumb-down", "id":"tooComplicatedTooManySteps", "label":"Toocomplicated/toomanysteps" },{ "type":"thumb-down", "id":"outOfDate", "label":"Outofdate" },{ "type":"thumb-down", "id":"samplesCodeIssue", "label":"Samples/codeissue" },{ "type":"thumb-down", "id":"otherDown", "label":"Other" }] [{ "type":"thumb-up", "id":"easyToUnderstand", "label":"Easytounderstand" },{ "type":"thumb-up", "id":"solvedMyProblem", "label":"Solvedmyproblem" },{ "type":"thumb-up", "id":"otherUp", "label":"Other" }] GitHub TryGoogleAnalyticssamples StackOverflow Askquestionsusingthegoogle-analyticstag Twitter Follow@googleanalyticsonTwitter Videos ViewGoogleAnalyticsvideosonYouTube Connect Community&Updates GettingHelp ReportinganIssue ProductInfo Protocol/SDKPolicy BrandingPolicy Developerconsoles GoogleAPIConsole GoogleCloudPlatformConsole GooglePlayConsole FirebaseConsole ActionsonGoogleConsole CastSDKDeveloperConsole ChromeWebStoreDashboard Android Chrome Firebase GoogleCloudPlatform Allproducts Terms Privacy SignupfortheGoogleDevelopersnewsletter Subscribe Language English BahasaIndonesia Deutsch Español Français Português–Brasil Русский 中文–简体 日本語 한국어
延伸文章資訊
- 1Why are you using Google Analytics API v3 rather than v4
As per this announcement by Google, there is no harm in using the older version as long as you do...
- 2google-api-services-analytics - Maven Repository
Home » com.google.apis » google-api-services-analytics. Google Analytics API V3 Rev169 1.25.0. Go...
- 3Core Reporting API - Reference Guide - Google Developers
Authorization: Bearer {oauth2-token} GET https://www.googleapis.com/analytics/v3/data/ga ?ids=ga:...
- 4Google Analytics Reporting API v3 R functions
Google Analytics Reporting API v3 R functions ... New API features will no longer occur for the v...
- 5Google.Apis.Analytics.v3 1.57.0.1679 - NuGet