Usage | laravel-analytics-rust | Spatie       

 SPATIE  

laravel-analytics-rust
======================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-analytics-rust](https://spatie.be/docs/laravel-analytics-rust/v1)  Usage

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-analytics-rust/v1) 

  Usage    
- [ Introduction ](https://spatie.be/docs/laravel-analytics-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-analytics-rust/v1/support-us)
- [ Installation ](https://spatie.be/docs/laravel-analytics-rust/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/laravel-analytics-rust/v1/usage)
- [ Testing ](https://spatie.be/docs/laravel-analytics-rust/v1/testing)
- [ Changelog ](https://spatie.be/docs/laravel-analytics-rust/v1/changelog)

 Usage
=====

###  On this page 

1. [ Date periods ](#content-date-periods)
2. [ Named reports ](#content-named-reports)
3. [ Custom queries ](#content-custom-queries)
4. [ Realtime reports ](#content-realtime-reports)
5. [ Errors ](#content-errors)

Date periods
--------------------------------------------------------------------------------------------

- `Period` includes both endpoints in the property's timezone. Supply today's date explicitly to avoid server-timezone and midnight races.
- `days(n, today)` includes today and the preceding n days. `months` and `years` clamp to the last valid day of shorter months.
- Reversed dates and arithmetic overflow return typed configuration errors.

```
use spatie_analytics::{Date, Period};

let today = Date::new(2024, 3, 31).unwrap();
let month = Period::months(1, today)?;
assert_eq!(month.start_date(), Date::new(2024, 2, 29).unwrap());
assert_eq!(Period::days(30, today)?.start_date(), Date::new(2024, 3, 1).unwrap());
```

Named reports
-----------------------------------------------------------------------------------------------

- Pass a positive row limit and a zero-based offset to paginated reports.
- Counts are `u64`. Negative or malformed counts return errors; missing dates stay missing.
- Daily active users are not additive. Use `fetch_period_totals` for distinct active users across a whole period. A successful empty totals response yields zero counts.
- Ranked reports sort by pageviews descending, with dimension tie-breakers. Dates sort oldest first.
- Page-title and URL variants remain separate rows. GA4's `full_page_url` can omit the scheme and include a query string.
- Labels such as `(not set)` and empty referrers are preserved.

These calls compile but require a configured client and property access to execute:

```
let daily = analytics.fetch_total_visitors_and_page_views(period, 31, 0).await?;
let totals = analytics.fetch_period_totals(period).await?;
let pages = analytics.fetch_most_visited_pages(period, 200, 0).await?;
let referrers = analytics.fetch_top_referrers(period, 20, 0).await?;
let countries = analytics.fetch_top_countries(period, 15, 0).await?;
let visitors = analytics.fetch_visitors_and_page_views(period, 10, 0).await?;
let by_date = analytics.fetch_visitors_and_page_views_by_date(period, 10, 0).await?;
let browsers = analytics.fetch_top_browsers(period, 10, 0).await?;
let systems = analytics.fetch_top_operating_systems(period, 10, 0).await?;
let user_types = analytics.fetch_user_types(period).await?;
```

- `max_results` limits the total across pages. `offset` must leave room for that limit in Google's signed int64 range.
- Standard reports follow pages until the limit or `rowCount`, including short intermediate pages. Requests are not a snapshot transaction; changing data can shift rows.
- `set_property_id` validates a new property without rebuilding authentication and preserves the original property on error. Cache entries remain separated by property.

Custom queries
--------------------------------------------------------------------------------------------------

- Build queries fluently or edit their public options directly. Defaults are ten results, zero offset, no filters or sorting, and no empty rows.
- Each `order_by` call appends a column in precedence order. Filter setters replace the corresponding Google `FilterExpression`.
- Query validation runs on execution, before cache access or network requests.

```
use serde_json::json;
use spatie_analytics::{OrderBy, Query};

let query = Query::new(["activeUsers", "screenPageViews"], ["country", "city"])
    .max_results(100)
    .offset(20)
    .order_by(OrderBy::metric("activeUsers", true))
    .order_by(OrderBy::dimension("city", false))
    .dimension_filter(json!({
        "filter": {"fieldName": "country", "stringFilter": {"matchType": "EXACT", "value": "Belgium"}}
    }))
    .keep_empty_rows(true);
```

Execute against a configured client:

```
let rows = analytics.get(period, query).await?;
```

- Results are `ReportRow` maps keyed by column name. `ReportValue` distinguishes dates, nonnegative counts, and strings.
- Known user/pageview metrics become counts; `date` becomes a calendar date. Unknown columns, including decimal metrics, keep their original string representation.
- `dimension_filter` and `metric_filter` accept nested AND/OR/NOT expressions in Google's JSON format.
- Standard custom queries share named reports' pagination and cache behavior.

Realtime reports
--------------------------------------------------------------------------------------------------------

- `MinuteRange` selects minutes 0 through 29, inclusive, for standard GA4 properties. The start is the older minute and must be at least the end.
- Realtime supports filters, sorting, and a result limit, but not offsets or empty rows. Unsupported options return `ConfigurationError::RealtimeOptions`.
- Realtime issues one request. `page_size` affects only standard reports. Use a short cache lifetime or no cache when freshness matters.

```
use spatie_analytics::{MinuteRange, Query};

let query = Query::new(["activeUsers"], ["country"]).max_results(100);
let rows = analytics.get_realtime(MinuteRange::create(29, 0)?, &query).await?;
```

Errors
--------------------------------------------------------------------------

- Report methods return `Result<_, Error>`. No failure becomes an empty report.
- Match `Error::Configuration(ConfigurationError::...)` for invalid settings and `Error::InvalidReport(ReportError::...)` for malformed report data.
- API errors retain HTTP status, Google's status/message, and numeric Retry-After seconds. Authentication, transport, JSON, clock, credential, storage, and cache failures have separate variants.
- Missing files and invalid keys fail construction or first provider resolution. Missing Google permissions fail the report request.
- Applications choose whether to retry, serve stale data, or log a failure.

```
use spatie_analytics::{Config, ConfigurationError, Error};

assert!(matches!(
    Config::new("G-not-a-property-id"),
    Err(Error::Configuration(ConfigurationError::PropertyId))
));
```

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
