toggl

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 23, 2026 License: Apache-2.0 Imports: 9 Imported by: 0

README

go-toggl

A modern Go client library for the Toggl Track API v9.

codecov

Installation

go get github.com/shoekstra/go-toggl

Usage

package main

import (
  "context"
  "log"

  "github.com/shoekstra/go-toggl"
)

func main() {
  client, err := toggl.NewClient("your-api-token")
  if err != nil {
    log.Fatal(err)
  }

  te, resp, err := client.TimeEntries.GetTimeEntry(context.Background(), 12345)
  if err != nil {
    log.Fatal(err)
  }
  log.Printf("time entry %d (status %d)", te.ID, resp.StatusCode)
}

Pagination

List endpoints that support pagination accept Page and PerPage options. The Response returned by every method includes a Pagination field with metadata parsed from response headers.

Page-based pagination
perPage := 50
page := 1
for {
    projects, resp, err := client.Projects.ListProjects(ctx, workspaceID, &toggl.ListProjectsOptions{
        Page:    toggl.Int(page),
        PerPage: toggl.Int(perPage),
    })
    if err != nil {
        log.Fatal(err)
    }
    // process projects...

    // TotalPages is 0 when the endpoint does not return X-Pages header;
    // in that case stop when the page returns fewer items than requested.
    if resp.Pagination.TotalPages > 0 && resp.Pagination.CurrentPage >= resp.Pagination.TotalPages {
        break
    }
    if resp.Pagination.TotalPages == 0 && len(projects) < perPage {
        break
    }
    page++
}
Cursor-based pagination (detailed reports)

The detailed reports endpoint uses cursor-based pagination via the X-Next-ID and X-Next-Row-Number response headers.

var firstID, firstRowNumber *int
for {
    entries, resp, err := client.Reports.DetailedReport(ctx, workspaceID, &toggl.DetailedReportOptions{
        FirstID:        firstID,
        FirstRowNumber: firstRowNumber,
    })
    if err != nil {
        log.Fatal(err)
    }
    // process entries...

    if resp.Pagination.NextID == 0 {
        break
    }
    firstID = toggl.Int(resp.Pagination.NextID)
    firstRowNumber = toggl.Int(resp.Pagination.NextRowNumber)
}

Services

  • TimeEntries - Time entry management
  • Projects - Project management
  • Tags - Tag management
  • Clients - Client management
  • Workspaces - Workspace information
  • Reports - Report generation (Reports API)

Development

Prerequisites
Common Tasks
# Run all tests
task test

# Format code
task fmt

# Run linter
task lint

# Run everything: fmt, vet, lint, test
task all

# View coverage
task test:coverage

# Clean build artifacts
task clean

License

Apache License 2.0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bool

func Bool(b bool) *bool

Bool returns a pointer to the provided bool value.

func Float64

func Float64(f float64) *float64

Float64 returns a pointer to the provided float64 value.

func Int

func Int(i int) *int

Int returns a pointer to the provided int value.

func String

func String(s string) *string

String returns a pointer to the provided string value.

func Time

func Time(t time.Time) *time.Time

Time returns a pointer to the provided time.Time value.

Types

type ArchiveResponse

type ArchiveResponse struct {
	Items []int `json:"items"`
}

ArchiveResponse is the response from ClientsService.ArchiveClient. Items contains the IDs of projects archived alongside the client.

type BillableRate

type BillableRate struct {
	BillableSeconds int    `json:"billable_seconds"`
	Currency        string `json:"currency"`
	HourlyRateCents int    `json:"hourly_rate_in_cents"`
}

BillableRate represents an hourly rate with associated billable seconds.

type Client

type Client struct {

	// Services
	TimeEntries *TimeEntriesService
	Projects    *ProjectsService
	Tags        *TagsService
	Clients     *ClientsService
	Workspaces  *WorkspacesService
	Reports     *ReportsService
	// contains filtered or unexported fields
}

Client is the Toggl Track API client.

func NewClient

func NewClient(token string, opts ...ClientOption) (*Client, error)

NewClient creates a new Toggl API client with the given token.

Use the functional options (WithBaseURL, WithHTTPClient, WithTimeout) to customise the client. When WithTimeout is used it takes effect regardless of whether WithHTTPClient appears before or after it. When only WithHTTPClient is provided, the custom client's existing Timeout is preserved; if the custom client has no timeout set, defaultTimeout is applied.

type ClientOption

type ClientOption func(*Client)

ClientOption is a functional option for configuring the Client.

func WithBaseURL

func WithBaseURL(baseURL string) ClientOption

WithBaseURL sets the base URL for API requests.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) ClientOption

WithHTTPClient sets the HTTP client for API requests. A nil value is ignored and the default client is retained.

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout sets the timeout for API requests. It can be used alongside WithHTTPClient in any order; the timeout is always applied after all options are processed. Passing zero explicitly disables the timeout.

type ClientsService

type ClientsService struct {
	// contains filtered or unexported fields
}

ClientsService handles operations related to clients.

func (*ClientsService) ArchiveClient

func (s *ClientsService) ArchiveClient(ctx context.Context, workspaceID, clientID int) (*ArchiveResponse, *Response, error)

ArchiveClient archives a client and its related projects. This is a premium workspace feature.

API: POST /api/v9/workspaces/{workspace_id}/clients/{client_id}/archive

See: https://engineering.toggl.com/docs/api/clients#post-archive-client

func (*ClientsService) CreateClient

func (s *ClientsService) CreateClient(ctx context.Context, workspaceID int, opts *CreateClientOptions) (*TogglClient, *Response, error)

CreateClient creates a new client in the given workspace.

API: POST /api/v9/workspaces/{workspace_id}/clients

See: https://engineering.toggl.com/docs/api/clients#post-create-client

func (*ClientsService) DeleteClient

func (s *ClientsService) DeleteClient(ctx context.Context, workspaceID, clientID int) (*Response, error)

DeleteClient deletes a client from the given workspace.

API: DELETE /api/v9/workspaces/{workspace_id}/clients/{client_id}

See: https://engineering.toggl.com/docs/api/clients#delete-delete-client

func (*ClientsService) GetClient

func (s *ClientsService) GetClient(ctx context.Context, workspaceID, clientID int) (*TogglClient, *Response, error)

GetClient gets a single client by ID.

API: GET /api/v9/workspaces/{workspace_id}/clients/{client_id}

See: https://engineering.toggl.com/docs/api/clients#get-load-client-by-id

func (*ClientsService) ListClients

func (s *ClientsService) ListClients(ctx context.Context, workspaceID int, opts *ListClientsOptions) ([]*TogglClient, *Response, error)

ListClients lists all clients in the given workspace.

API: GET /api/v9/workspaces/{workspace_id}/clients

See: https://engineering.toggl.com/docs/api/clients#get-list-clients

func (*ClientsService) RestoreClient

func (s *ClientsService) RestoreClient(ctx context.Context, workspaceID, clientID int, opts *RestoreClientOptions) (*TogglClient, *Response, error)

RestoreClient restores an archived client and optionally its projects.

API: POST /api/v9/workspaces/{workspace_id}/clients/{client_id}/restore

See: https://engineering.toggl.com/docs/api/clients#post-restore-client

func (*ClientsService) UpdateClient

func (s *ClientsService) UpdateClient(ctx context.Context, workspaceID, clientID int, opts *UpdateClientOptions) (*TogglClient, *Response, error)

UpdateClient updates an existing client.

API: PUT /api/v9/workspaces/{workspace_id}/clients/{client_id}

See: https://engineering.toggl.com/docs/api/clients#put-change-client

type CreateClientOptions

type CreateClientOptions struct {
	// Name is required. The client name.
	Name string
	// Notes is an optional free-text note.
	Notes *string
	// ExternalReference is an optional reference to an external system.
	ExternalReference *string
}

CreateClientOptions specifies the parameters to ClientsService.CreateClient.

type CreateProjectOptions

type CreateProjectOptions struct {
	// Name is required. The project name.
	Name string
	// Active sets the project as active or archived.
	Active *bool
	// Billable marks the project as billable (premium feature).
	Billable *bool
	// ClientID associates the project with a client.
	ClientID *int
	// Color is the project color in hex format (e.g. "#06aaf5").
	Color *string
	// Currency sets the project currency (premium feature).
	Currency *string
	// EndDate is the project end date in YYYY-MM-DD format.
	EndDate *string
	// EstimatedHours is the estimated number of hours for the project.
	EstimatedHours *int
	// FixedFee is the fixed fee for the project (premium feature).
	FixedFee *float64
	// IsPrivate controls whether the project is private.
	IsPrivate *bool
	// Rate is the hourly rate for the project (premium feature).
	Rate *float64
	// StartDate is the project start date in YYYY-MM-DD format.
	StartDate *string
	// Template marks the project as a template.
	Template *bool
	// TemplateID creates the project from a template.
	TemplateID *int
}

CreateProjectOptions specifies the parameters to ProjectsService.CreateProject.

type CreateTagOptions

type CreateTagOptions struct {
	// Name is required. The tag name.
	Name string
}

CreateTagOptions specifies the parameters to TagsService.CreateTag.

type CreateTimeEntryOptions

type CreateTimeEntryOptions struct {
	// Start is required. The start time of the entry in UTC.
	Start time.Time
	// Description is an optional time entry description.
	Description *string
	// ProjectID is an optional project association.
	ProjectID *int
	// TaskID is an optional task association.
	TaskID *int
	// Billable marks the entry as billable.
	Billable *bool
	// Tags are names of tags to apply. New tags are created automatically.
	Tags []string
	// TagIDs are IDs of tags to apply.
	TagIDs []int
	// Stop is the optional stop time. If omitted the entry runs until stopped.
	Stop *time.Time
	// Duration in seconds. Defaults to -1 (running entry) when not set.
	// If Stop and Duration are both provided they must satisfy start+duration==stop.
	Duration *int
	// CreatedWith identifies the application creating the entry.
	// Defaults to "go-toggl" when empty.
	CreatedWith string
}

CreateTimeEntryOptions specifies the parameters to TimeEntriesService.CreateTimeEntry.

type DetailedExportOptions

type DetailedExportOptions struct {
	DetailedReportOptions
	// DateFormat controls the date format in the export.
	// Valid values: "MM/DD/YYYY", "DD-MM-YYYY", "MM-DD-YYYY", "YYYY-MM-DD",
	// "DD/MM/YYYY", "DD.MM.YYYY".
	DateFormat *string `json:"date_format,omitempty"`
	// DurationFormat controls the duration format.
	// Valid values: "classic", "decimal", "improved". Defaults to "classic".
	DurationFormat *string `json:"duration_format,omitempty"`
	// DisplayMode controls how date/time is displayed in the PDF.
	// Valid values: "date_only", "time_only", "date_time", "date_and_time".
	DisplayMode *string `json:"display_mode,omitempty"`
	// HourFormat controls the hour format in the PDF.
	HourFormat *string `json:"hour_format,omitempty"`
	// CentsSeparator sets the separator character for cent values.
	CentsSeparator *string `json:"cents_separator,omitempty"`
}

DetailedExportOptions specifies the parameters to ReportsService.ExportDetailedPDF and ReportsService.ExportDetailedCSV.

type DetailedReportOptions

type DetailedReportOptions struct {
	ReportFilters
	// OrderBy sets the sort column.
	// Valid values: "date", "user", "duration", "description", "last_update".
	// Defaults to "date".
	OrderBy *string `json:"order_by,omitempty"`
	// OrderDir sets the sort direction. Valid values: "ASC", "DESC".
	OrderDir *string `json:"order_dir,omitempty"`
	// PageSize sets the number of entries per page. Defaults to 50.
	PageSize *int `json:"page_size,omitempty"`
	// Grouped groups time entries together. Defaults to false.
	Grouped *bool `json:"grouped,omitempty"`
	// EnrichResponse returns the maximum amount of information. Defaults to false.
	EnrichResponse *bool `json:"enrich_response,omitempty"`
	// HideAmounts omits monetary amounts from the response.
	HideAmounts *bool `json:"hide_amounts,omitempty"`
	// FirstID is the cursor ID for pagination (from X-Next-ID response header).
	FirstID *int `json:"first_id,omitempty"`
	// FirstRowNumber is the cursor row number for pagination
	// (from X-Next-Row-Number response header).
	FirstRowNumber *int `json:"first_row_number,omitempty"`
	// FirstTimestamp is the cursor timestamp for pagination.
	FirstTimestamp *int `json:"first_timestamp,omitempty"`
}

DetailedReportOptions specifies the parameters to ReportsService.DetailedReport and ReportsService.DetailedReportTotals.

type DetailedTimeEntry

type DetailedTimeEntry struct {
	Billable            bool     `json:"billable"`
	BillableAmountCents *int     `json:"billable_amount_in_cents"`
	ClientName          *string  `json:"client_name"`
	Currency            *string  `json:"currency"`
	Description         *string  `json:"description"`
	HourlyRateCents     *int     `json:"hourly_rate_in_cents"`
	ProjectColor        *string  `json:"project_color"`
	ProjectHex          *string  `json:"project_hex"`
	ProjectID           *int     `json:"project_id"`
	ProjectName         *string  `json:"project_name"`
	RowNumber           int      `json:"row_number"`
	TagIDs              []int    `json:"tag_ids"`
	TagNames            []string `json:"tag_names"`
	UserID              *int     `json:"user_id"`
	Username            *string  `json:"username"`
}

DetailedTimeEntry is a single time entry row in a detailed report.

type ErrorResponse

type ErrorResponse struct {
	StatusCode int
	Message    string
	Response   *http.Response
}

ErrorResponse represents an API error response.

func (*ErrorResponse) Error

func (e *ErrorResponse) Error() string

Error implements the error interface.

type ListClientsOptions

type ListClientsOptions struct {
	// Status filters clients by status. Valid values: "active", "archived", "both".
	// Defaults to "active" when not set.
	Status *string
	// Name filters clients by name (case-insensitive).
	Name *string
	// Page is the page number for pagination.
	Page *int
	// PerPage is the number of results per page.
	PerPage *int
}

ListClientsOptions specifies the optional parameters to ClientsService.ListClients.

type ListProjectsOptions

type ListProjectsOptions struct {
	// Active filters by project status. Valid values: "true", "false", "both".
	// Defaults to "true" when not set.
	Active *string
	// Billable filters by billable status (premium feature).
	Billable *bool
	// Name filters projects by name.
	Name *string
	// Since filters projects modified since this UNIX timestamp.
	Since *int64
	// Page is the page number for pagination.
	Page *int
	// PerPage is the number of results per page.
	PerPage *int
}

ListProjectsOptions specifies the optional parameters to ProjectsService.ListProjects.

type ListTagsOptions

type ListTagsOptions struct {
	// Search filters tags by name (case-insensitive substring match).
	Search *string
	// Page is the page number for pagination.
	Page *int
	// PerPage is the number of results per page.
	PerPage *int
}

ListTagsOptions specifies the optional parameters to TagsService.ListTags.

type ListTimeEntriesOptions

type ListTimeEntriesOptions struct {
	// Since filters entries modified since this UNIX timestamp (includes deleted).
	Since *int64
	// Before filters entries with start time before this date (YYYY-MM-DD or RFC3339).
	Before *string
	// StartDate filters entries with start time from this date (YYYY-MM-DD or RFC3339).
	// Use together with EndDate.
	StartDate *string
	// EndDate filters entries with start time until this date (YYYY-MM-DD or RFC3339).
	// Use together with StartDate.
	EndDate *string
}

ListTimeEntriesOptions specifies the optional parameters to TimeEntriesService.ListTimeEntries.

type Pagination

type Pagination struct {
	// CurrentPage is the current page number (X-Page header).
	CurrentPage int
	// TotalPages is the total number of pages (X-Pages header).
	TotalPages int
	// PageSize is the number of items per page (X-Page-Size header).
	PageSize int
	// NextID is the cursor for the next page of detailed report results (X-Next-ID header).
	NextID int
	// NextRowNumber is the row number cursor for the next page of detailed report results (X-Next-Row-Number header).
	NextRowNumber int
}

Pagination contains pagination metadata parsed from API response headers.

Not all endpoints populate every field. The page-based fields (CurrentPage, TotalPages, PageSize) are set when the response includes X-Page, X-Pages, and X-Page-Size headers. The cursor-based fields (NextID, NextRowNumber) are set for the detailed reports endpoint via X-Next-ID and X-Next-Row-Number headers.

To iterate through all pages using page-based pagination:

perPage := 50
page := 1
for {
    items, resp, err := client.Projects.ListProjects(ctx, wsID, &toggl.ListProjectsOptions{
        Page:    toggl.Int(page),
        PerPage: toggl.Int(perPage),
    })
    if err != nil {
        return err
    }
    // process items...
    if resp.Pagination.TotalPages > 0 && resp.Pagination.CurrentPage >= resp.Pagination.TotalPages {
        break
    }
    if resp.Pagination.TotalPages == 0 && len(items) < perPage {
        break
    }
    page++
}

To iterate through detailed report pages using cursor-based pagination:

var firstID, firstRowNumber *int
for {
    opts := &toggl.DetailedReportOptions{FirstID: firstID, FirstRowNumber: firstRowNumber}
    entries, resp, err := client.Reports.DetailedReport(ctx, wsID, opts)
    if err != nil {
        return err
    }
    // process entries...
    if resp.Pagination.NextID == 0 {
        break
    }
    firstID = toggl.Int(resp.Pagination.NextID)
    firstRowNumber = toggl.Int(resp.Pagination.NextRowNumber)
}

type Project

type Project struct {
	ID               int       `json:"id"`
	Name             string    `json:"name"`
	WorkspaceID      int       `json:"workspace_id"`
	ClientID         *int      `json:"client_id"`
	Active           bool      `json:"active"`
	IsPrivate        bool      `json:"is_private"`
	Billable         *bool     `json:"billable"`
	AutoEstimates    *bool     `json:"auto_estimates"`
	EstimatedHours   *int      `json:"estimated_hours"`
	EstimatedSeconds *int      `json:"estimated_seconds"`
	ActualHours      *int      `json:"actual_hours"`
	ActualSeconds    *int      `json:"actual_seconds"`
	Color            string    `json:"color"`
	Rate             float64   `json:"rate"`
	RateLastUpdated  *string   `json:"rate_last_updated"`
	Currency         *string   `json:"currency"`
	Template         *bool     `json:"template"`
	TemplateID       *int      `json:"template_id"`
	FixedFee         float64   `json:"fixed_fee"`
	StartDate        *string   `json:"start_date"`
	EndDate          *string   `json:"end_date"`
	At               time.Time `json:"at"`
	CreatedAt        time.Time `json:"created_at"`
}

Project represents a Toggl project.

type ProjectsService

type ProjectsService struct {
	// contains filtered or unexported fields
}

ProjectsService handles operations related to projects.

func (*ProjectsService) CreateProject

func (s *ProjectsService) CreateProject(ctx context.Context, workspaceID int, opts *CreateProjectOptions) (*Project, *Response, error)

CreateProject creates a new project in the given workspace.

API: POST /api/v9/workspaces/{workspace_id}/projects

See: https://engineering.toggl.com/docs/api/projects#post-workspaceprojects

func (*ProjectsService) DeleteProject

func (s *ProjectsService) DeleteProject(ctx context.Context, workspaceID, projectID int, teDeletionMode *string) (*Response, error)

DeleteProject deletes a project from the given workspace.

The optional teDeletionMode controls what happens to time entries linked to this project: "delete" removes them, "unassign" removes the project association but keeps the entries. When not set the server default applies.

API: DELETE /api/v9/workspaces/{workspace_id}/projects/{project_id}

See: https://engineering.toggl.com/docs/api/projects#delete-workspaceproject

func (*ProjectsService) GetProject

func (s *ProjectsService) GetProject(ctx context.Context, workspaceID, projectID int) (*Project, *Response, error)

GetProject gets a single project by ID.

API: GET /api/v9/workspaces/{workspace_id}/projects/{project_id}

See: https://engineering.toggl.com/docs/api/projects#get-workspaceproject

func (*ProjectsService) ListProjects

func (s *ProjectsService) ListProjects(ctx context.Context, workspaceID int, opts *ListProjectsOptions) ([]*Project, *Response, error)

ListProjects lists all projects in the given workspace.

API: GET /api/v9/workspaces/{workspace_id}/projects

See: https://engineering.toggl.com/docs/api/projects#get-workspaceprojects

func (*ProjectsService) UpdateProject

func (s *ProjectsService) UpdateProject(ctx context.Context, workspaceID, projectID int, opts *UpdateProjectOptions) (*Project, *Response, error)

UpdateProject updates an existing project.

API: PUT /api/v9/workspaces/{workspace_id}/projects/{project_id}

See: https://engineering.toggl.com/docs/api/projects#put-workspaceproject

type ReportFilters

type ReportFilters struct {
	// StartDate is the report start date (YYYY-MM-DD).
	StartDate *string `json:"start_date,omitempty"`
	// EndDate is the report end date (YYYY-MM-DD). Must be after StartDate.
	EndDate *string `json:"end_date,omitempty"`
	// ClientIDs filters by client. Pass a slice containing 0 to include
	// entries with no client.
	ClientIDs []int `json:"client_ids,omitempty"`
	// ProjectIDs filters by project. Pass a slice containing 0 to include
	// entries with no project.
	ProjectIDs []int `json:"project_ids,omitempty"`
	// UserIDs filters by user.
	UserIDs []int `json:"user_ids,omitempty"`
	// TagIDs filters by tag. Pass a slice containing 0 to include entries
	// with no tags.
	TagIDs []int `json:"tag_ids,omitempty"`
	// GroupIDs filters by user group.
	GroupIDs []int `json:"group_ids,omitempty"`
	// TaskIDs filters by task.
	TaskIDs []int `json:"task_ids,omitempty"`
	// TimeEntryIDs filters to specific time entry IDs.
	TimeEntryIDs []int `json:"time_entry_ids,omitempty"`
	// Description filters by description text.
	Description *string `json:"description,omitempty"`
	// Billable filters by billable status (premium feature).
	Billable *bool `json:"billable,omitempty"`
	// Rounding controls time rounding. Defaults to user preferences.
	Rounding *int `json:"rounding,omitempty"`
	// RoundingMinutes sets the rounding interval in minutes.
	// Valid values: 0, 1, 5, 6, 10, 12, 15, 30, 60, 240.
	RoundingMinutes *int `json:"rounding_minutes,omitempty"`
	// MinDurationSeconds filters out entries shorter than this value (Time Audit).
	MinDurationSeconds *int `json:"min_duration_seconds,omitempty"`
	// MaxDurationSeconds filters out entries longer than this value (Time Audit).
	MaxDurationSeconds *int `json:"max_duration_seconds,omitempty"`
}

ReportFilters holds the common filtering fields shared across all report types. Embed this struct in a report-specific options type.

type ReportsService

type ReportsService struct {
	// contains filtered or unexported fields
}

ReportsService handles operations related to reports. It uses the Reports API v3 base path (/reports/api/v3/) rather than the standard API v9 path used by other services.

func (*ReportsService) DetailedReport

func (s *ReportsService) DetailedReport(ctx context.Context, workspaceID int, opts *DetailedReportOptions) ([]*DetailedTimeEntry, *Response, error)

DetailedReport returns individual time entries for the given workspace matching the provided filters. Pagination is cursor-based: read the X-Next-ID and X-Next-Row-Number response headers and pass them back as FirstID and FirstRowNumber in subsequent calls.

API: POST /reports/api/v3/workspace/{workspace_id}/search/time_entries

See: https://engineering.toggl.com/docs/reports/detailed

func (*ReportsService) DetailedReportTotals

func (s *ReportsService) DetailedReportTotals(ctx context.Context, workspaceID int, opts *DetailedReportOptions) (*TotalsReport, *Response, error)

DetailedReportTotals returns the aggregate totals for a detailed report, including total seconds, billable amounts, and a day-by-day graph.

API: POST /reports/api/v3/workspace/{workspace_id}/search/time_entries/totals

See: https://engineering.toggl.com/docs/reports/detailed

func (*ReportsService) ExportDetailedCSV

func (s *ReportsService) ExportDetailedCSV(ctx context.Context, workspaceID int, opts *DetailedExportOptions) ([]byte, *Response, error)

ExportDetailedCSV downloads a detailed report as a CSV file.

API: POST /reports/api/v3/workspace/{workspace_id}/search/time_entries.csv

See: https://engineering.toggl.com/docs/reports/detailed

func (*ReportsService) ExportDetailedPDF

func (s *ReportsService) ExportDetailedPDF(ctx context.Context, workspaceID int, opts *DetailedExportOptions) ([]byte, *Response, error)

ExportDetailedPDF downloads a detailed report as a PDF file.

API: POST /reports/api/v3/workspace/{workspace_id}/search/time_entries.pdf

See: https://engineering.toggl.com/docs/reports/detailed

func (*ReportsService) ExportSummaryCSV

func (s *ReportsService) ExportSummaryCSV(ctx context.Context, workspaceID int, opts *SummaryExportOptions) ([]byte, *Response, error)

ExportSummaryCSV downloads a summary report as a CSV file. To download as XLSX, use the same options but the underlying path ends in .xlsx — see the Toggl Reports API documentation.

API: POST /reports/api/v3/workspace/{workspace_id}/summary/time_entries.csv

See: https://engineering.toggl.com/docs/reports/summary

func (*ReportsService) ExportSummaryPDF

func (s *ReportsService) ExportSummaryPDF(ctx context.Context, workspaceID int, opts *SummaryExportOptions) ([]byte, *Response, error)

ExportSummaryPDF downloads a summary report as a PDF file.

API: POST /reports/api/v3/workspace/{workspace_id}/summary/time_entries.pdf

See: https://engineering.toggl.com/docs/reports/summary

func (*ReportsService) ExportWeeklyCSV

func (s *ReportsService) ExportWeeklyCSV(ctx context.Context, workspaceID int, opts *WeeklyExportOptions) ([]byte, *Response, error)

ExportWeeklyCSV downloads a weekly report as a CSV file.

API: POST /reports/api/v3/workspace/{workspace_id}/weekly/time_entries.csv

See: https://engineering.toggl.com/docs/reports/weekly

func (*ReportsService) ExportWeeklyPDF

func (s *ReportsService) ExportWeeklyPDF(ctx context.Context, workspaceID int, opts *WeeklyExportOptions) ([]byte, *Response, error)

ExportWeeklyPDF downloads a weekly report as a PDF file.

API: POST /reports/api/v3/workspace/{workspace_id}/weekly/time_entries.pdf

See: https://engineering.toggl.com/docs/reports/weekly

func (*ReportsService) SummaryReport

func (s *ReportsService) SummaryReport(ctx context.Context, workspaceID int, opts *SummaryReportOptions) (*SummaryReportData, *Response, error)

SummaryReport returns aggregated time data for the given workspace grouped according to the provided options.

API: POST /reports/api/v3/workspace/{workspace_id}/summary/time_entries

See: https://engineering.toggl.com/docs/reports/summary

func (*ReportsService) WeeklyReport

func (s *ReportsService) WeeklyReport(ctx context.Context, workspaceID int, opts *WeeklyReportOptions) ([]*WeeklyReportEntry, *Response, error)

WeeklyReport returns a week-by-week breakdown of tracked time for the given workspace.

API: POST /reports/api/v3/workspace/{workspace_id}/weekly/time_entries

See: https://engineering.toggl.com/docs/reports/weekly

type Response

type Response struct {
	StatusCode int
	Headers    http.Header
	Body       []byte
	Response   *http.Response
	Pagination Pagination
}

Response wraps the standard http.Response with additional context.

type RestoreClientOptions

type RestoreClientOptions struct {
	// RestoreAllProjects restores all projects linked to the client.
	RestoreAllProjects *bool
	// Projects is a list of specific project IDs to restore alongside the client.
	Projects []int
}

RestoreClientOptions specifies the optional parameters to ClientsService.RestoreClient.

type SummaryAudit

type SummaryAudit struct {
	// GroupFilter restricts which groups appear in the audit view.
	GroupFilter *SummaryAuditFilter `json:"group_filter,omitempty"`
	// ShowEmptyGroups includes groups with no tracked time.
	ShowEmptyGroups *bool `json:"show_empty_groups,omitempty"`
	// ShowTrackedGroups includes groups with tracked time.
	ShowTrackedGroups *bool `json:"show_tracked_groups,omitempty"`
}

SummaryAudit configures the Time Audit view for a summary report.

type SummaryAuditFilter

type SummaryAuditFilter struct {
	// Currency filters by currency code.
	Currency *string `json:"currency,omitempty"`
	// MaxAmountCents is the upper billable amount bound in cents.
	MaxAmountCents *int `json:"max_amount_cents,omitempty"`
	// MaxDurationSeconds is the upper duration bound in seconds.
	MaxDurationSeconds *int `json:"max_duration_seconds,omitempty"`
	// MinAmountCents is the lower billable amount bound in cents.
	MinAmountCents *int `json:"min_amount_cents,omitempty"`
	// MinDurationSeconds is the lower duration bound in seconds.
	MinDurationSeconds *int `json:"min_duration_seconds,omitempty"`
}

SummaryAuditFilter constrains entries shown in the Time Audit group.

type SummaryExportOptions

type SummaryExportOptions struct {
	SummaryReportOptions
	// DateFormat controls the date format in the export.
	// Valid values: "MM/DD/YYYY", "DD-MM-YYYY", "MM-DD-YYYY", "YYYY-MM-DD",
	// "DD/MM/YYYY", "DD.MM.YYYY". Defaults to "MM/DD/YYYY".
	DateFormat *string `json:"date_format,omitempty"`
	// DurationFormat controls the duration format.
	// Valid values: "classic", "decimal", "improved". Defaults to "classic".
	DurationFormat *string `json:"duration_format,omitempty"`
	// OrderBy sets the sort column. Valid values: "title", "duration".
	OrderBy *string `json:"order_by,omitempty"`
	// OrderDir sets the sort direction. Valid values: "ASC", "DESC".
	OrderDir *string `json:"order_dir,omitempty"`
	// Collapse collapses other entries. Defaults to false.
	Collapse *bool `json:"collapse,omitempty"`
	// HideRates omits rate information from the export.
	HideRates *bool `json:"hide_rates,omitempty"`
	// HideAmounts omits monetary amounts from the export.
	HideAmounts *bool `json:"hide_amounts,omitempty"`
	// CentsSeparator sets the separator character for cent values.
	CentsSeparator *string `json:"cents_separator,omitempty"`
	// Resolution sets the graph resolution (PDF only).
	Resolution *string `json:"resolution,omitempty"`
}

SummaryExportOptions specifies the parameters to ReportsService.ExportSummaryPDF and ReportsService.ExportSummaryCSV.

type SummaryGroup

type SummaryGroup struct {
	ID        *int              `json:"id"`
	Seconds   int               `json:"seconds"`
	Rates     []BillableRate    `json:"rates"`
	SubGroups []SummarySubGroup `json:"sub_groups"`
}

SummaryGroup is a top-level grouping in a summary report.

type SummaryReportData

type SummaryReportData struct {
	Groups []SummaryGroup `json:"groups"`
}

SummaryReportData is the response from ReportsService.SummaryReport.

type SummaryReportOptions

type SummaryReportOptions struct {
	ReportFilters
	// Grouping sets the top-level grouping (e.g. "projects", "clients", "users").
	Grouping *string `json:"grouping,omitempty"`
	// SubGrouping sets the secondary grouping.
	SubGrouping *string `json:"sub_grouping,omitempty"`
	// DistinguishRates creates sub-groups for each billing rate.
	DistinguishRates *bool `json:"distinguish_rates,omitempty"`
	// IncludeTimeEntryIDs includes time entry IDs in the response.
	IncludeTimeEntryIDs *bool `json:"include_time_entry_ids,omitempty"`
	// Audit configures the Time Audit view.
	Audit *SummaryAudit `json:"audit,omitempty"`
}

SummaryReportOptions specifies the parameters to ReportsService.SummaryReport.

type SummarySubGroup

type SummarySubGroup struct {
	ID      *int           `json:"id"`
	Seconds int            `json:"seconds"`
	Rates   []BillableRate `json:"rates"`
	Title   *string        `json:"title"`
}

SummarySubGroup is a sub-grouping within a SummaryGroup.

type Tag

type Tag struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
	// WorkspaceID is the workspace this tag belongs to (json: "workspace_id").
	WorkspaceID int `json:"workspace_id"`
	// Workspace is an alias for WorkspaceID retained for backwards compatibility.
	Workspace          int        `json:"-"`
	CreatorID          int        `json:"creator_id"`
	At                 time.Time  `json:"at"`
	DeletedAt          *time.Time `json:"deleted_at"`
	IntegrationExtID   *string    `json:"integration_ext_id"`
	IntegrationExtType *string    `json:"integration_ext_type"`
	Permissions        []string   `json:"permissions"`
}

Tag represents a Toggl tag.

func (*Tag) UnmarshalJSON

func (t *Tag) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for Tag, accepting both "workspace_id" (current API) and "workspace" (legacy) and keeping both WorkspaceID and Workspace in sync.

type TagsService

type TagsService struct {
	// contains filtered or unexported fields
}

TagsService handles operations related to tags.

func (*TagsService) CreateTag

func (s *TagsService) CreateTag(ctx context.Context, workspaceID int, opts *CreateTagOptions) (*Tag, *Response, error)

CreateTag creates a new tag in the given workspace.

API: POST /api/v9/workspaces/{workspace_id}/tags

See: https://engineering.toggl.com/docs/api/tags#post-create-tag

func (*TagsService) DeleteTag

func (s *TagsService) DeleteTag(ctx context.Context, workspaceID, tagID int) (*Response, error)

DeleteTag deletes a tag from the given workspace.

API: DELETE /api/v9/workspaces/{workspace_id}/tags/{tag_id}

See: https://engineering.toggl.com/docs/api/tags#delete-delete-tag

func (*TagsService) ListTags

func (s *TagsService) ListTags(ctx context.Context, workspaceID int, opts *ListTagsOptions) ([]*Tag, *Response, error)

ListTags lists all tags in the given workspace.

API: GET /api/v9/workspaces/{workspace_id}/tags

See: https://engineering.toggl.com/docs/api/tags#get-tags

func (*TagsService) UpdateTag

func (s *TagsService) UpdateTag(ctx context.Context, workspaceID, tagID int, opts *UpdateTagOptions) (*Tag, *Response, error)

UpdateTag updates an existing tag. The name is required.

API: PUT /api/v9/workspaces/{workspace_id}/tags/{tag_id}

See: https://engineering.toggl.com/docs/api/tags#put-update-tag

type TimeEntriesService

type TimeEntriesService struct {
	// contains filtered or unexported fields
}

TimeEntriesService handles operations related to time entries.

func (*TimeEntriesService) CreateTimeEntry

func (s *TimeEntriesService) CreateTimeEntry(ctx context.Context, workspaceID int, opts *CreateTimeEntryOptions) (*TimeEntry, *Response, error)

CreateTimeEntry creates a new time entry in the given workspace.

API: POST /api/v9/workspaces/{workspace_id}/time_entries

See: https://engineering.toggl.com/docs/api/time_entries#post-timeentries

func (*TimeEntriesService) DeleteTimeEntry

func (s *TimeEntriesService) DeleteTimeEntry(ctx context.Context, workspaceID, entryID int) (*Response, error)

DeleteTimeEntry deletes a time entry.

API: DELETE /api/v9/workspaces/{workspace_id}/time_entries/{time_entry_id}

See: https://engineering.toggl.com/docs/api/time_entries#delete-timeentries

func (*TimeEntriesService) GetRunningTimeEntry

func (s *TimeEntriesService) GetRunningTimeEntry(ctx context.Context) (*TimeEntry, *Response, error)

GetRunningTimeEntry returns the currently running time entry, if any. Returns a 404 error when no entry is running.

API: GET /api/v9/me/time_entries/current

See: https://engineering.toggl.com/docs/api/time_entries#get-get-current-time-entry

func (*TimeEntriesService) GetTimeEntry

func (s *TimeEntriesService) GetTimeEntry(ctx context.Context, entryID int) (*TimeEntry, *Response, error)

GetTimeEntry gets a single time entry by ID.

API: GET /api/v9/me/time_entries/{time_entry_id}

See: https://engineering.toggl.com/docs/api/time_entries#get-get-a-time-entry-by-id

func (*TimeEntriesService) ListTimeEntries

func (s *TimeEntriesService) ListTimeEntries(ctx context.Context, opts *ListTimeEntriesOptions) ([]*TimeEntry, *Response, error)

ListTimeEntries lists the current user's time entries with optional filters.

API: GET /api/v9/me/time_entries

See: https://engineering.toggl.com/docs/api/time_entries#get-timeentries

func (*TimeEntriesService) StartTimeEntry

func (s *TimeEntriesService) StartTimeEntry(ctx context.Context, workspaceID int, opts *CreateTimeEntryOptions) (*TimeEntry, *Response, error)

StartTimeEntry creates a new running time entry in the given workspace. It is a convenience wrapper around CreateTimeEntry that always sets duration=-1 and clears any stop time, ensuring the entry is running.

API: POST /api/v9/workspaces/{workspace_id}/time_entries

See: https://engineering.toggl.com/docs/api/time_entries#post-timeentries

func (*TimeEntriesService) StopTimeEntry

func (s *TimeEntriesService) StopTimeEntry(ctx context.Context, workspaceID, entryID int) (*TimeEntry, *Response, error)

StopTimeEntry stops a running time entry.

API: PATCH /api/v9/workspaces/{workspace_id}/time_entries/{time_entry_id}/stop

See: https://engineering.toggl.com/docs/api/time_entries#patch-stop-timeentry

func (*TimeEntriesService) UpdateTimeEntry

func (s *TimeEntriesService) UpdateTimeEntry(ctx context.Context, workspaceID, entryID int, opts *UpdateTimeEntryOptions) (*TimeEntry, *Response, error)

UpdateTimeEntry updates an existing time entry.

API: PUT /api/v9/workspaces/{workspace_id}/time_entries/{time_entry_id}

See: https://engineering.toggl.com/docs/api/time_entries#put-timeentries

type TimeEntry

type TimeEntry struct {
	ID          int        `json:"id"`
	Description *string    `json:"description"`
	ProjectID   *int       `json:"project_id"`
	TaskID      *int       `json:"task_id"`
	ClientID    *int       `json:"client_id"`
	WorkspaceID int        `json:"workspace_id"`
	UserID      int        `json:"user_id"`
	Billable    bool       `json:"billable"`
	TagIDs      []int      `json:"tag_ids"`
	Tags        []string   `json:"tags"`
	Start       time.Time  `json:"start"`
	Stop        *time.Time `json:"stop"`
	Duration    int        `json:"duration"`
	CreatedWith string     `json:"created_with"`
	At          time.Time  `json:"at"`
}

TimeEntry represents a time entry in Toggl.

type TogglClient

type TogglClient struct {
	ID                int       `json:"id"`
	Name              string    `json:"name"`
	WorkspaceID       int       `json:"wid"`
	Notes             *string   `json:"notes"`
	Archived          bool      `json:"archived"`
	At                time.Time `json:"at"`
	CreatorID         int       `json:"creator_id"`
	ExternalReference *string   `json:"external_reference"`
	Permissions       []string  `json:"permissions"`
}

TogglClient represents a Toggl client (customer/organization).

type TotalsGraph

type TotalsGraph struct {
	BillableAmountCents int `json:"billable_amount_in_cents"`
	LabourCostCents     int `json:"labour_cost_in_cents"`
	Seconds             int `json:"seconds"`
}

TotalsGraph is a single data point in the TotalsReport graph.

type TotalsReport

type TotalsReport struct {
	BillableAmountCents int            `json:"billable_amount_in_cents"`
	LabourCostCents     int            `json:"labour_cost_in_cents"`
	Seconds             int            `json:"seconds"`
	TrackedDays         int            `json:"tracked_days"`
	Resolution          string         `json:"resolution"`
	Graph               []TotalsGraph  `json:"graph"`
	Rates               []BillableRate `json:"rates"`
}

TotalsReport is the response from ReportsService.DetailedReportTotals.

type UpdateClientOptions

type UpdateClientOptions struct {
	// Name updates the client name.
	Name *string
	// Notes updates the free-text note.
	Notes *string
	// ExternalReference updates the external system reference.
	ExternalReference *string
}

UpdateClientOptions specifies the optional parameters to ClientsService.UpdateClient.

type UpdateProjectOptions

type UpdateProjectOptions struct {
	// Name updates the project name.
	Name *string
	// Active sets the project as active or archived.
	Active *bool
	// Billable marks the project as billable (premium feature).
	Billable *bool
	// ClientID updates the client association.
	ClientID *int
	// Color updates the project color in hex format.
	Color *string
	// Currency updates the project currency (premium feature).
	Currency *string
	// EndDate updates the project end date in YYYY-MM-DD format.
	EndDate *string
	// EstimatedHours updates the estimated number of hours.
	EstimatedHours *int
	// FixedFee updates the fixed fee (premium feature).
	FixedFee *float64
	// IsPrivate controls whether the project is private.
	IsPrivate *bool
	// Rate updates the hourly rate (premium feature).
	Rate *float64
	// StartDate updates the project start date in YYYY-MM-DD format.
	StartDate *string
	// Template marks the project as a template.
	Template *bool
}

UpdateProjectOptions specifies the optional parameters to ProjectsService.UpdateProject.

type UpdateTagOptions

type UpdateTagOptions struct {
	// Name is required. The new tag name.
	Name string
}

UpdateTagOptions specifies the parameters to TagsService.UpdateTag.

type UpdateTimeEntryOptions

type UpdateTimeEntryOptions struct {
	// Description updates the time entry description.
	Description *string
	// ProjectID updates the project association.
	ProjectID *int
	// TaskID updates the task association.
	TaskID *int
	// Billable updates the billable flag.
	Billable *bool
	// Tags are tag names to add or remove (see TagAction).
	Tags []string
	// TagIDs are tag IDs to add or remove (see TagAction).
	TagIDs []int
	// TagAction is "add" or "delete". Controls how Tags/TagIDs are applied.
	TagAction *string
	// Start updates the start time.
	Start *time.Time
	// Stop updates the stop time.
	Stop *time.Time
	// Duration updates the duration in seconds.
	Duration *int
}

UpdateTimeEntryOptions specifies the optional parameters to TimeEntriesService.UpdateTimeEntry.

type UpdateWorkspaceOptions

type UpdateWorkspaceOptions struct {
	// Name updates the workspace name.
	Name *string
	// Admins replaces the list of workspace admin user IDs.
	Admins []int
	// DefaultCurrency updates the default currency (premium feature).
	DefaultCurrency *string
	// DefaultHourlyRate updates the default hourly rate (premium feature).
	DefaultHourlyRate *float64
	// OnlyAdminsMayCreateProjects restricts project creation to admins.
	OnlyAdminsMayCreateProjects *bool
	// OnlyAdminsMayCreateTags restricts tag creation to admins.
	OnlyAdminsMayCreateTags *bool
	// OnlyAdminsSeeDashboard restricts the team dashboard to admins.
	OnlyAdminsSeeDashboard *bool
	// ProjectsBillableByDefault sets new projects as billable by default (premium feature).
	ProjectsBillableByDefault *bool
	// ProjectsEnforceBillable enforces the billable setting when tracking time to projects.
	ProjectsEnforceBillable *bool
	// ProjectsPrivateByDefault sets new projects as private by default.
	ProjectsPrivateByDefault *bool
	// LimitPublicProjectData limits public project data in reports to admins.
	LimitPublicProjectData *bool
	// RateChangeMode controls how rate changes are applied (premium feature).
	// Valid values: "start-today", "override-current", "override-all".
	RateChangeMode *string
	// ReportsCollapse sets whether reports are collapsed by default.
	ReportsCollapse *bool
	// Rounding sets the default rounding (premium feature).
	// Values: 0 = nearest, 1 = round up, -1 = round down.
	Rounding *int
	// RoundingMinutes sets the default rounding interval in minutes (premium feature).
	RoundingMinutes *int
}

UpdateWorkspaceOptions specifies the optional parameters to WorkspacesService.UpdateWorkspace.

type WeeklyExportOptions

type WeeklyExportOptions struct {
	WeeklyReportOptions
	// Calculate sets the calculation mode. Valid values: "by time", "amounts".
	Calculate *string `json:"calculate,omitempty"`
	// GroupByTask groups entries by planned task. Defaults to false.
	GroupByTask *bool `json:"group_by_task,omitempty"`
	// Grouping sets the grouping option.
	Grouping *string `json:"grouping,omitempty"`
	// DateFormat controls the date format in the PDF export.
	// Valid values: "MM/DD/YYYY", "DD-MM-YYYY", "MM-DD-YYYY", "YYYY-MM-DD",
	// "DD/MM/YYYY", "DD.MM.YYYY". Defaults to "MM/DD/YYYY".
	DateFormat *string `json:"date_format,omitempty"`
	// DurationFormat controls the duration format.
	// Valid values: "classic", "decimal", "improved". Defaults to "classic".
	DurationFormat *string `json:"duration_format,omitempty"`
	// LogoURL sets the URL of the logo to include in the PDF.
	LogoURL *string `json:"logo_url,omitempty"`
	// CentsSeparator sets the separator character for cent values.
	CentsSeparator *string `json:"cents_separator,omitempty"`
}

WeeklyExportOptions specifies the parameters to ReportsService.ExportWeeklyPDF and ReportsService.ExportWeeklyCSV.

type WeeklyReportEntry

type WeeklyReportEntry struct {
	ProjectID *int    `json:"project_id"`
	ClientID  *int    `json:"client_id"`
	UserID    *int    `json:"user_id"`
	Title     *string `json:"title"`
	Seconds   []int   `json:"seconds"`
}

WeeklyReportEntry is a single row in a weekly report.

type WeeklyReportOptions

type WeeklyReportOptions struct {
	ReportFilters
}

WeeklyReportOptions specifies the parameters to ReportsService.WeeklyReport.

type Workspace

type Workspace struct {
	ID                          int       `json:"id"`
	Name                        string    `json:"name"`
	OrganizationID              int       `json:"organization_id"`
	ActiveProjectCount          int       `json:"active_project_count"`
	At                          time.Time `json:"at"`
	Premium                     bool      `json:"premium"`
	BusinessWs                  bool      `json:"business_ws"`
	DefaultCurrency             string    `json:"default_currency"`
	DefaultHourlyRate           *float64  `json:"default_hourly_rate"`
	OnlyAdminsMayCreateProjects bool      `json:"only_admins_may_create_projects"`
	OnlyAdminsMayCreateTags     bool      `json:"only_admins_may_create_tags"`
	OnlyAdminsSeeDashboard      bool      `json:"only_admins_see_team_dashboard"`
	ProjectsBillableByDefault   bool      `json:"projects_billable_by_default"`
	ProjectsEnforceBillable     bool      `json:"projects_enforce_billable"`
	ProjectsPrivateByDefault    bool      `json:"projects_private_by_default"`
	ReportsCollapse             bool      `json:"reports_collapse"`
	Rounding                    int       `json:"rounding"`
	RoundingMinutes             int       `json:"rounding_minutes"`
	LogoURL                     *string   `json:"logo_url"`
	IcalEnabled                 bool      `json:"ical_enabled"`
	IcalURL                     *string   `json:"ical_url"`
	Role                        string    `json:"role"`
	Permissions                 []string  `json:"permissions"`
}

Workspace represents a Toggl workspace.

type WorkspacesService

type WorkspacesService struct {
	// contains filtered or unexported fields
}

WorkspacesService handles operations related to workspaces.

func (*WorkspacesService) GetWorkspace

func (s *WorkspacesService) GetWorkspace(ctx context.Context, workspaceID int) (*Workspace, *Response, error)

GetWorkspace gets a single workspace by ID.

API: GET /api/v9/workspaces/{workspace_id}

See: https://engineering.toggl.com/docs/api/workspaces#get-get-single-workspace

func (*WorkspacesService) ListWorkspaces

func (s *WorkspacesService) ListWorkspaces(ctx context.Context) ([]*Workspace, *Response, error)

ListWorkspaces lists all workspaces for the current user.

API: GET /api/v9/me/workspaces

See: https://engineering.toggl.com/docs/api/me#get-workspaces

func (*WorkspacesService) UpdateWorkspace

func (s *WorkspacesService) UpdateWorkspace(ctx context.Context, workspaceID int, opts *UpdateWorkspaceOptions) (*Workspace, *Response, error)

UpdateWorkspace updates a workspace.

API: PUT /api/v9/workspaces/{workspace_id}

See: https://engineering.toggl.com/docs/api/workspaces#put-update-workspace

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL