#google-trends-api

[![NPM](https://nodei.co/npm/google-trends-api.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/google-trends-api/)

[![npm version](https://badge.fury.io/js/google-trends-api.svg)](https://badge.fury.io/js/google-trends-api)
[![Build status](https://img.shields.io/travis/pat310/google-trends-api.svg?style=flat-square)](https://travis-ci.org/pat310/google-trends-api/)
[![Coverage Status](https://coveralls.io/repos/github/pat310/google-trends-api/badge.svg?branch=master)](https://coveralls.io/github/pat310/google-trends-api?branch=master)
[![Code Climate](https://codeclimate.com/github/pat310/google-trends-api/badges/gpa.svg)](https://codeclimate.com/github/pat310/google-trends-api)
[![Dependency Status](https://img.shields.io/david/pat310/google-trends-api.svg?style=flat-square)](https://david-dm.org/pat310/google-trends-api)
[![Known Vulnerabilities](https://snyk.io/test/github/pat310/google-trends-api/badge.svg)](https://snyk.io/test/github/pat310/google-trends-api)

##v3 to v4
[Big changes](/CHANGES.md)!  The old google-trends endpoints are deprecated and are heavily throttled so this library has changed significantly.  You can choose to download the old version via `npm install google-trends-api@3.0.2` but it is discouraged.

##Introduction
This library provides an API layer to [google trends](https://www.google.com/trends/) data.  It is constantly being expanded and improved so please check back frequently.  Also, please feel free to contribute to make the library even better! :dog:

###Syntax
```js
const googleTrends = require('google-trends-api');

googleTrends.apiMethod(optionsObject, [callback])
```

####Parameters
**optionsObject**
An object with the following options keys:
* **keyword** Target search term (string) **required**
* **startTime** Start of time period of interest (`new Date()` object).  If `startTime` is not provided, a date of January 1, 2004 is assumed (this is the oldest available google trends data)
* **endTime** End of time period of interest (`new Date()` object). If `endTime` is not provided, the current date is selected.
* **geo** Location of interest (string).
* **hl** Preferred language (defaults to english)
* **resolution** Granularity of the geo search (enumerated string ['COUNTRY', 'REGION', 'CITY', 'DMA']).  `resolution` is specific to the [interestByRegion](#interestByRegion) method.

**callback**
Optional callback function where the first parameter is an error and the second parameter is the result.  If no callback is provided, then a promise is returned.

##Table of contents
* [Installation](#installation)
* [API](#api)
  * [Promises](#promises)
  * [Callbacks](#callbacks)
  * [Examples](#examples)
  * [API Methods](#api-methods)
    * [interestOverTime](#interestovertime)
    * [interestByRegion](#interestbyregion)
    * [relatedQueries](#relatedqueries)
    * [relatedTopics](#relatedtopics)
* [Geo help](#geo-help)
* [Big Thanks](#big-thanks)

<hr>

## Installation
To install this package, clone this git repository and include it in your project's node_modules or simply:

```
npm install google-trends-api
```

Require google-trends-api in your script and give it a variable name:

```js
const googleTrends = require('google-trends-api');
```

You will now be able to access methods on `googleTrends`.  See the [API Methods section](#api-methods) below to see the methods available and their syntax.

[back to top](#introduction)

<hr>

## API

### Promises
By default, all the API's return a promise for the results.  Example:
```js
googleTrends.interestOverTime({keyword: 'Women\'s march'})
.then(function(results){
  console.log('These results are awesome', results);
})
.catch(function(err){
  console.error('Oh no there was an error', err);
});
```

### Callbacks
All API methods can alternatively take a callback function as the second parameter.  For example:
```js
googleTrends.interestOverTime({keyword: 'Women\'s march'}, function(err, results){
  if(err) console.error('there was an error!', err);
  else console.log('my sweet sweet results', results);
})
```

### Examples
There are examples available for each API method in the root directory of the module.  **Note:** Each example in [examples.js](/examples.js) needs to be uncommented.

### API Methods
The following API methods are available:
* [interestOverTime](#interestovertime): Numbers represent search interest relative to the highest point on the chart for the given region and time. A value of 100 is the peak popularity for the term. A value of 50 means that the term is half as popular. Likewise a score of 0 means the term was less than 1% as popular as the peak.'

* [interestByRegion](#interestbyregion): See in which location your term was most popular during the specified time frame. Values are calculated on a scale from 0 to 100, where 100 is the location with the most popularity as a fraction of total searches in that location, a value of 50 indicates a location which is half as popular, and a value of 0 indicates a location where the term was less than 1% as popular as the peak. <p><p> **Note:** A higher value means a higher proportion of all queries, not a higher absolute query count. So a tiny country where 80% of the queries are for "bananas" will get twice the score of a giant country where only 40% of the queries are for "bananas".


* [relatedQueries](#relatedqueries): Users searching for your term also searched for these queries. The following metrics are returned:
  * **Top** - The most popular search queries. Scoring is on a relative scale where a value of 100 is the most commonly searched query, 50 is a query searched half as often, and a value of 0 is a query searched for less than 1% as often as the most popular query.
  * **Rising** - Queries with the biggest increase in search frequency since the last time period. Results marked "Breakout" had a tremendous increase, probably because these queries are new and had few (if any) prior searches.

* [relatedTopics](#relatedtopics): Users searching for your term also searched for these topics. The following metrics are returned:
  * **Top** - The most popular topics. Scoring is on a relative scale where a value of 100 is the most commonly searched topic, a value of 50 is a topic searched half as often, and a value of 0 is a topic searched for less than 1% as often as the most popular topic.
  * **Rising** - Related topics with the biggest increase in search frequency since the last time period. Results marked "Breakout" had a tremendous increase, probably because these topics are new and had few (if any) prior searches.

[back to top](#introduction)

<hr>

#### interestOverTime
*Search interest relative to the highest point on the chart for the given region and time (100 is the peak popularity for the term)*

#####Syntax
`googleTrends.interestOverTime({keyword: string, startTime: Date, endTime: Date, geo: string}, cbFunc)`

Requires an `object` as the first parameter with the following keys:
* `keyword` - **required** - type `string` - the search term of interest
* `startTime` - *optional* - type `Date` object - the start of the time range of interest (defaults to `new Date('2004-01-01')` if not supplied)
* `endTime` - *optional* - type `Date` object - the end of the time range of interest (defaults to `new Date(Date.now())` if not supplied)
* `geo` - *optional* - type `string` - geocode for a country, region, or DMA depending on the granularity required (defaults to worldwide).  For example, `geo: 'US-CA-800'` will target the Bakersfield, California, United States or `geo: 'US'` will just target the US.
* `hl` - *optional* - type `string` - preferred language code for results (defaults to english)

Optional callback `function` as the second parameter (otherwise returns a promise)

The resolution of the search changes automatically depending on the search duration.  The wider the duration window, the worse the resolution (for example, a search duration with a `startTime` and `endTime` that ends years apart will return a resolution in months, while a search duration with a `startTime` and `endTime` a few hours apart will return a resolution in minutes).

#####Example 1
Returning the search interest over time for 'Valentines Day' (by default from 2004-01-01 to today)

######Input
```js
googleTrends.interestOverTime({keyword: 'Valentines Day'})
.then(function(results){
  console.log(results);
})
.catch(function(err){
  console.error(err);
});
```

######Output
```js
{"default":{"timelineData":[{"time":"1072915200","formattedTime":"Jan 2004","formattedAxisTime":"Jan 1, 2004","value":[26],"formattedValue":["26"]},{"time":"1075593600","formattedTime":"Feb 2004","formattedAxisTime":"Feb 1, 2004","value":[74],"formattedValue":["74"]},
...
{"time":"1483228800","formattedTime":"Jan 2017","formattedAxisTime":"Jan 1, 2017","value":[18],"formattedValue":["18"]},{"time":"1485907200","formattedTime":"Feb 2017","formattedAxisTime":"Feb 1, 2017","value":[72],"formattedValue":["72"]}],"averages":[]}}
```

#####Example 2
Returning the search interest over time for 'Valentines Day' from the past four hours.  Note that the resolution is by minute since our query duration is shorter.

######Input
```js
googleTrends.interestOverTime({keyword: 'Valentines Day', startTime: new Date(Date.now() - (4 * 60 * 60 * 1000))}, function(err, results) {
  if (err) console.log('oh no error!', err);
  else console.log(results);
});
```

######Output
```js
{"default":{"timelineData":[{"time":"1487026800","formattedTime":"Feb 13, 2017 at 6:00 PM","formattedAxisTime":"6:00 PM","value":[49],"formattedValue":["49"]},{"time":"1487026860","formattedTime":"Feb 13, 2017 at 6:01 PM","formattedAxisTime":"6:01 PM","value":[50],"formattedValue":["50"]},
...
{"time":"1487040180","formattedTime":"Feb 13, 2017 at 9:43 PM","formattedAxisTime":"9:43 PM","value":[88],"formattedValue":["88"]},{"time":"1487040240","formattedTime":"Feb 13, 2017 at 9:44 PM","formattedAxisTime":"9:44 PM","value":[81],"formattedValue":["81"]}],"averages":[]}}
```

[back to top](#introduction)

<hr>

#### interestByRegion
*See in which location your term was most popular during the specified time frame. Values are calculated on a scale from 0 to 100, where 100 is the location with the most popularity as a fraction of total searches in that location.*

#####Syntax
`googleTrends.interestByRegion({keyword: string, startTime: Date, endTime: Date, geo: string, resolution: string}, cbFunc)`

Requires an `object` as the first parameter with the following keys:
* `keyword` - **required** - type `string` - the search term of interest
* `startTime` - *optional* - type `Date` object - the start of the time range of interest (defaults to `new Date('2004-01-01')` if not supplied)
* `endTime` - *optional* - type `Date` object - the end of the time range of interest (defaults to `new Date(Date.now())` if not supplied)
* `geo` - *optional* - type `string` - geocode for a country, region, or DMA depending on the granularity required (defaults to worldwide).  For example, `geo: 'US-CA-800'` will target the Bakersfield, California, United States or `geo: 'US'` will just target the US.
* `resolution` - *optional* - type `enumerated string` either `COUNTRY`, `REGION`, `CITY` or `DMA`.  Resolution is selected by default otherwise.  Trying to select a resolution larger than a specified `geo` will return an error.
* `hl` - *optional* - type `string` - preferred language code for results (defaults to english)

Optional callback `function` as the second parameter (otherwise returns a promise)

#####Example 1
Returning the search interest by cities around the world for 'Donald Trump' from February 01, 2017 to February 06, 2017.

######Input
```js
googleTrends.interestByRegion({keyword: 'Donald Trump', startTime: new Date('2017-02-01'), endTime: new Date('2017-02-06'), resolution: 'CITY'})
.then((res) => {
  console.log(res);
})
.catch((err) => {
  console.log(err);
})
```

######Output
```js
{"default":{"geoMapData":[{"coordinates":{"lat":18.594395,"lng":-72.3074326},"geoName":"Port-au-Prince","value":[100],"formattedValue":["100"],"maxValueIndex":0},{"coordinates":{"lat":43.467517,"lng":-79.6876659},"geoName":"Oakville","value":[90],"formattedValue":["90"],"maxValueIndex":0},
...
{"coordinates":{"lat":40.9312099,"lng":-73.8987469},"geoName":"Yonkers","value":[69],"formattedValue":["69"],"maxValueIndex":0}]}}
```

#####Example 2
Returning the search interest by cities in California for 'Donald Trump' from February 01, 2017 to February 06, 2017.

######Input
```js
googleTrends.interestByRegion({keyword: 'Donald Trump', startTime: new Date('2017-02-01'), endTime: new Date('2017-02-06'), geo: 'US-CA'})
.then((res) => {
  console.log(res);
})
.catch((err) => {
  console.log(err);
})
```

######Output
```js
{"default":{"geoMapData":[{"geoCode":"807","geoName":"San Francisco-Oakland-San Jose CA","value":[100],"formattedValue":["100"],"maxValueIndex":0},{"geoCode":"828","geoName":"Monterey-Salinas CA","value":[100],"formattedValue":["100"],"maxValueIndex":0},
...
{"geoCode":"811","geoName":"Reno NV","value":[12],"formattedValue":["12"],"maxValueIndex":0},{"geoCode":"813","geoName":"Medford-Klamath Falls OR","value":[4],"formattedValue":["4"],"maxValueIndex":0}]}}
```

[back to top](#introduction)

<hr>

#### relatedQueries
*Users searching for your term also searched for these queries.*

#####Syntax
`googleTrends.relatedQueries({keyword: string, startTime: Date, endTime: Date, geo: string}, cbFunc)`

Requires an `object` as the first parameter with the following keys:
* `keyword` - **required** - type `string` - the search term of interest
* `startTime` - *optional* - type `Date` object - the start of the time range of interest (defaults to `new Date('2004-01-01')` if not supplied)
* `endTime` - *optional* - type `Date` object - the end of the time range of interest (defaults to `new Date(Date.now())` if not supplied)
* `geo` - *optional* - type `string` - geocode for a country, region, or DMA depending on the granularity required (defaults to worldwide).  For example, `geo: 'US-CA-800'` will target the Bakersfield, California, United States or `geo: 'US'` will just target the US.
* `hl` - *optional* - type `string` - preferred language code for results (defaults to english)

Optional callback `function` as the second parameter (otherwise returns a promise)

#####Example
Returning top related queries for 'Westminster Dog show' with default startTime, endTime, and geo categories

######Input
```js
googleTrends.relatedQueries({keyword: 'Westminster Dog Show'})
.then((res) => {
  console.log(res);
})
.catch((err) => {
  console.log(err);
})
```

######Output
```js
{"default":{"rankedList":[{"rankedKeyword":[{"query":"dog show 2016","value":100,"formattedValue":"100","link":"/"},{"query":"2016 westminster dog show","value":95,"formattedValue":"95","link":"/"},
...
{"query":"dogs","value":20,"formattedValue":"20","link":"/"}]},{"rankedKeyword":[{"query":"dog show 2016","value":836500,"formattedValue":"Breakout","link":"/"},{"query":"2016 westminster dog show","value":811550,"formattedValue":"Breakout","link":"/"},
...
{"query":"who won the westminster dog show","value":59000,"formattedValue":"Breakout","link":"/"}]}]}}
```

[back to top](#introduction)

<hr>

#### relatedTopics
*Users searching for your term also searched for these topics*

#####Syntax
`googleTrends.relatedTopics({keyword: string, startTime: Date, endTime: Date, geo: string}, cbFunc)`

Requires an `object` as the first parameter with the following keys:
* `keyword` - **required** - type `string` - the search term of interest
* `startTime` - *optional* - type `Date` object - the start of the time range of interest (defaults to `new Date('2004-01-01')` if not supplied)
* `endTime` - *optional* - type `Date` object - the end of the time range of interest (defaults to `new Date(Date.now())` if not supplied)
* `geo` - *optional* - type `string` - geocode for a country, region, or DMA depending on the granularity required (defaults to worldwide).  For example, `geo: 'US-CA-800'` will target the Bakersfield, California, United States or `geo: 'US'` will just target the US.
* `hl` - *optional* - type `string` - preferred language code for results (defaults to english)

Optional callback `function` as the second parameter (otherwise returns a promise)

#####Example
Returning top related topics for 'Chipotle' from January 1st, 2015 to February 10th, 2017.

######Input
```js
googleTrends.relatedTopics({keyword: 'Chipotle', startTime: new Date('2015-01-01'), endTime: new Date('2017-02-10')})
.then((res) => {
  console.log(res);
})
.catch((err) => {
  console.log(err);
})
```

######Output
```js
{"default":{"rankedList":[{"rankedKeyword":[{"topic":{"mid":"/m/01b566","title":"Chipotle Mexican Grill","type":"Restaurant company"},"value":100,"formattedValue":"100","link":"/"},{"topic":{"mid":"/m/02f217","title":"Chipotle","type":"Jalape\u00f1o"},"value":5,"formattedValue":"5","link":"/"},
...
{"topic":{"mid":"/m/01xg7s","title":"Chorizo","type":"Topic"},"value":0,"formattedValue":"0","link":"/"}]},{"rankedKeyword":[{"topic":{"mid":"/m/09_yl","title":"E. coli","type":"Bacteria"},"value":40700,"formattedValue":"Breakout","link":"/"},
...
{"topic":{"mid":"/m/0dqc4","title":"Caridea","type":"Animal"},"value":40,"formattedValue":"+40%","link":"/"}]}]}}
```

[back to top](#introduction)

<hr>
##Geo help
Unfortunately support is not offered for zip codes at this time.  The user must enter a country code, region (or state) code, and/or DMA (Designated Market Area) code.

* A list of country codes can be found here: [country code list](https://github.com/datasets/country-codes/blob/master/data/country-codes.csv)
* A list of DMAs can be found here: [DMA list](https://support.google.com/richmedia/answer/2745487?hl=en)
* A list of available languages can be found here: [language codes](https://sites.google.com/site/tomihasa/google-language-codes)

<hr>

##Big Thanks
* To [dreyco676](https://github.com/dreyco676) for the heads up on the deprecated routes and new end points.  Checkout the [python google trends](https://github.com/GeneralMills/pytrends)

[back to top](#introduction)
