postivo

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2025 License: MIT Imports: 14 Imported by: 0

README

Go Reference GitHub Release GitHub License Static Badge

POSTIVO.PL REST API Client SDK for Go

This package provides the POSTIVO.PL Hybrid Mail Services SDK for Go, allowing you to dispatch shipments directly from your application via the POSTIVO.PL platform.

Additional documentation:

Comprehensive documentation of all methods and types is available below in Available Resources and Operations.

You can also refer to the REST API v1 documentation for additional details about this SDK.

Table of Contents

SDK Installation

To add the SDK as a dependency to your project:

go get github.com/postivo/go-client

SDK Example Usage

Sending Shipment to single recipient

This example demonstrates simple sending Shipment to a single recipient:

package main

import (
	"context"
	postivo "github.com/postivo/go-client"
	"github.com/postivo/go-client/models/components"
	"github.com/postivo/go-client/optionalnullable"
	"log"
)

func main() {
	ctx := context.Background()

	s := postivo.New(
		postivo.WithSecurity("<YOUR API ACCESS TOKEN>"),
	)

	res, err := s.Shipments.Dispatch(ctx, components.Shipment{
		Recipients: components.CreateShipmentRecipientsRecipients(
			components.CreateRecipientsRecipientInline(
				components.RecipientInline{
					Name:        postivo.Pointer("Jan Nowak"),
					Name2:       optionalnullable.From(postivo.Pointer("Firma testowa Sp. z o.o.")),
					Address:     postivo.Pointer("ul. Testowa"),
					HomeNumber:  optionalnullable.From(postivo.Pointer("23")),
					FlatNumber:  optionalnullable.From(postivo.Pointer("2")),
					PostCode:    postivo.Pointer("00-999"),
					City:        postivo.Pointer("Warszawa"),
					PhoneNumber: optionalnullable.From(postivo.Pointer("+48666666666")),
					Postscript:  optionalnullable.From(postivo.Pointer("Komunikat")),
					CustomID:    optionalnullable.From(postivo.Pointer("1234567890")),
				},
			),
		),
		Documents: components.CreateShipmentDocumentsArrayOfDocuments(
			[]components.Documents{
				components.CreateDocumentsDocumentPdf(
					components.DocumentPdf{
						FileStream: "<document_1 content encoded to base64>",
						FileName:   optionalnullable.From(postivo.Pointer("document1.pdf")),
					},
				),
				components.CreateDocumentsDocumentPdf(
					components.DocumentPdf{
						FileStream: "<document_2 content encoded to base64>",
						FileName:   optionalnullable.From(postivo.Pointer("document2.pdf")),
					},
				),
			},
		),
		Options: optionalnullable.From(postivo.Pointer(components.CreateOptionsObjShipmentOptions(
			components.ShipmentOptions{
				PredefinedConfigID: optionalnullable.From(postivo.Pointer[int64](2670)),
			},
		))),
	})
	if err != nil {
		log.Fatal(err)
	}
	if res.ShipmentDetails != nil {
		// handle response
	}
}

Checking the price of a shipment for single recipient

This example demonstrates simple checking the price of a Shipment to a single recipient:

package main

import (
	"context"
	postivo "github.com/postivo/go-client"
	"github.com/postivo/go-client/models/components"
	"github.com/postivo/go-client/optionalnullable"
	"log"
)

func main() {
	ctx := context.Background()

	s := postivo.New(
		postivo.WithSecurity("<YOUR API ACCESS TOKEN>"),
	)

	res, err := s.Shipments.Price(ctx, components.Shipment{
		Recipients: components.CreateShipmentRecipientsRecipients(
			components.CreateRecipientsRecipientInline(
				components.RecipientInline{
					Name:        postivo.Pointer("Jan Nowak"),
					Name2:       optionalnullable.From(postivo.Pointer("Firma testowa Sp. z o.o.")),
					Address:     postivo.Pointer("ul. Testowa"),
					HomeNumber:  optionalnullable.From(postivo.Pointer("23")),
					FlatNumber:  optionalnullable.From(postivo.Pointer("2")),
					PostCode:    postivo.Pointer("00-999"),
					City:        postivo.Pointer("Warszawa"),
					PhoneNumber: optionalnullable.From(postivo.Pointer("+48666666666")),
					Postscript:  optionalnullable.From(postivo.Pointer("Komunikat")),
					CustomID:    optionalnullable.From(postivo.Pointer("1234567890")),
				},
			),
		),
		Documents: components.CreateShipmentDocumentsArrayOfDocuments(
			[]components.Documents{
				components.CreateDocumentsDocumentPdf(
					components.DocumentPdf{
						FileStream: "<document_1 content encoded to base64>",
						FileName:   optionalnullable.From(postivo.Pointer("document1.pdf")),
					},
				),
				components.CreateDocumentsDocumentPdf(
					components.DocumentPdf{
						FileStream: "<document_2 content encoded to base64>",
						FileName:   optionalnullable.From(postivo.Pointer("document2.pdf")),
					},
				),
			},
		),
		Options: optionalnullable.From(postivo.Pointer(components.CreateOptionsObjShipmentOptions(
			components.ShipmentOptions{
				PredefinedConfigID: optionalnullable.From(postivo.Pointer[int64](2670)),
			},
		))),
	})
	if err != nil {
		log.Fatal(err)
	}
	if res.ShipmentPrices != nil {
		// handle response
	}
}

Authentication

Per-Client Security Schemes

This SDK supports the following security scheme globally:

Name Type Scheme Environment Variable
Bearer http HTTP Bearer CLIENT_BEARER

You can configure it using the WithSecurity option when initializing the SDK client instance. For example:

package main

import (
	"context"
	postivo "github.com/postivo/go-client"
	"log"
)

func main() {
	ctx := context.Background()

	s := postivo.New(
		postivo.WithSecurity("<YOUR API ACCESS TOKEN>"),
	)

	res, err := s.Accounts.Get(ctx)
	if err != nil {
		log.Fatal(err)
	}
	if res.AccountResponse != nil {
		// handle response
	}
}

Available Resources and Operations

Available methods
Accounts
AddressBook.Contacts
AddressBook.Contacts.ByExtID
  • Get - Retrieve contact details by EXT_ID
  • Update - Update a contact by EXT_ID
  • Delete - Delete a contact by EXT_ID
  • RemoveFromGroup - Remove a contact from a group by EXT_ID
  • AddToGroup - Add a contact to a group by EXT_ID
AddressBook.Groups
  • List - List groups
  • Add - Add a new group
  • Get - Retrieve group details
  • Update - Update a group
  • Delete - Delete a group
Common
  • Ping - Check API availability and version
Metadata
Senders
Shipments
  • Status - Retrieve shipment details with status events
  • Cancel - Cancel shipments
  • Dispatch - Dispatch a new shipment
  • Documents - Retrieve documents related to a shipment
  • Price - Check the shipment price

Retries

Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.

To change the default retry strategy for a single API call, simply provide a retry.Config object to the call by using the WithRetries option:

package main

import (
	"context"
	postivo "github.com/postivo/go-client"
	"github.com/postivo/go-client/retry"
	"log"
	"models/operations"
)

func main() {
	ctx := context.Background()

	s := postivo.New(
		postivo.WithSecurity("<YOUR API ACCESS TOKEN>"),
	)

	res, err := s.Accounts.Get(ctx, operations.WithRetries(
		retry.Config{
			Strategy: "backoff",
			Backoff: &retry.BackoffStrategy{
				InitialInterval: 1,
				MaxInterval:     50,
				Exponent:        1.1,
				MaxElapsedTime:  100,
			},
			RetryConnectionErrors: false,
		}))
	if err != nil {
		log.Fatal(err)
	}
	if res.AccountResponse != nil {
		// handle response
	}
}

If you'd like to override the default retry strategy for all operations that support retries, you can use the WithRetryConfig option at SDK initialization:

package main

import (
	"context"
	postivo "github.com/postivo/go-client"
	"github.com/postivo/go-client/retry"
	"log"
)

func main() {
	ctx := context.Background()

	s := postivo.New(
		postivo.WithRetryConfig(
			retry.Config{
				Strategy: "backoff",
				Backoff: &retry.BackoffStrategy{
					InitialInterval: 1,
					MaxInterval:     50,
					Exponent:        1.1,
					MaxElapsedTime:  100,
				},
				RetryConnectionErrors: false,
			}),
		postivo.WithSecurity("<YOUR API ACCESS TOKEN>"),
	)

	res, err := s.Accounts.Get(ctx)
	if err != nil {
		log.Fatal(err)
	}
	if res.AccountResponse != nil {
		// handle response
	}
}

Error Handling

Handling errors in this SDK should largely match your expectations. All operations return a response object or an error, they will never return both.

By Default, an API error will return apierrors.APIError. When custom error responses are specified for an operation, the SDK may also return their associated error. You can refer to respective Errors tables in SDK docs for more details on possible error types for each operation.

For example, the Get function may return the following errors:

Error Type Status Code Content Type
apierrors.ErrorResponse 401, 403, 4XX application/problem+json
apierrors.ErrorResponse 5XX application/problem+json
Example
package main

import (
	"context"
	"errors"
	postivo "github.com/postivo/go-client"
	"github.com/postivo/go-client/models/apierrors"
	"log"
)

func main() {
	ctx := context.Background()

	s := postivo.New(
		postivo.WithSecurity("<YOUR API ACCESS TOKEN>"),
	)

	res, err := s.Accounts.Get(ctx)
	if err != nil {

		var e *apierrors.ErrorResponse
		if errors.As(err, &e) {
			// handle error
			log.Fatal(e.Error())
		}

		var e *apierrors.ErrorResponse
		if errors.As(err, &e) {
			// handle error
			log.Fatal(e.Error())
		}

		var e *apierrors.APIError
		if errors.As(err, &e) {
			// handle error
			log.Fatal(e.Error())
		}
	}
}

Server Selection

Select Server by Name

You can override the default server globally using the WithServer(server string) option when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers:

Name Server Description
prod https://api.postivo.pl/rest/v1 Production system
sandbox https://api.postivo.pl/rest-sandbox/v1 Test system (SANDBOX)
Example
package main

import (
	"context"
	postivo "github.com/postivo/go-client"
	"log"
)

func main() {
	ctx := context.Background()

	s := postivo.New(
		postivo.WithServer("sandbox"),
		postivo.WithSecurity("<YOUR API ACCESS TOKEN>"),
	)

	res, err := s.Accounts.Get(ctx)
	if err != nil {
		log.Fatal(err)
	}
	if res.AccountResponse != nil {
		// handle response
	}
}

Override Server URL Per-Client

The default server can also be overridden globally using the WithServerURL(serverURL string) option when initializing the SDK client instance. For example:

package main

import (
	"context"
	postivo "github.com/postivo/go-client"
	"log"
)

func main() {
	ctx := context.Background()

	s := postivo.New(
		postivo.WithServerURL("https://api.postivo.pl/rest/v1"),
		postivo.WithSecurity("<YOUR API ACCESS TOKEN>"),
	)

	res, err := s.Accounts.Get(ctx)
	if err != nil {
		log.Fatal(err)
	}
	if res.AccountResponse != nil {
		// handle response
	}
}

Custom HTTP Client

The Go SDK makes API calls that wrap an internal HTTP client. The requirements for the HTTP client are very simple. It must match this interface:

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

The built-in net/http client satisfies this interface and a default client based on the built-in is provided by default. To replace this default with a client of your own, you can implement this interface yourself or provide your own client configured as desired. Here's a simple example, which adds a client with a 30 second timeout.

import (
	"net/http"
	"time"

	"github.com/postivo/go-client"
)

var (
	httpClient = &http.Client{Timeout: 30 * time.Second}
	sdkClient  = postivo.New(postivo.WithClient(httpClient))
)

This can be a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration.

Special Types

This SDK defines the following custom types to assist with marshalling and unmarshalling data.

Date

types.Date is a wrapper around time.Time that allows for JSON marshaling a date string formatted as "2006-01-02".

Usage
d1 := types.NewDate(time.Now()) // returns *types.Date

d2 := types.DateFromTime(time.Now()) // returns types.Date

d3, err := types.NewDateFromString("2019-01-01") // returns *types.Date, error

d4, err := types.DateFromString("2019-01-01") // returns types.Date, error

d5 := types.MustNewDateFromString("2019-01-01") // returns *types.Date and panics on error

d6 := types.MustDateFromString("2019-01-01") // returns types.Date and panics on error

Development

Maturity

This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.

Contributions

While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.

SDK Created by Speakeasy

Documentation

Index

Constants

View Source
const (
	// Production system
	ServerProd string = "prod"
	// Test system (SANDBOX)
	ServerSandbox string = "sandbox"
)

Variables

View Source
var ServerList = map[string]string{
	ServerProd:    "https://api.postivo.pl/rest/v1",
	ServerSandbox: "https://api.postivo.pl/rest-sandbox/v1",
}

ServerList contains the list of servers available to the SDK

Functions

func Bool

func Bool(b bool) *bool

Bool provides a helper function to return a pointer to a bool

func Float32

func Float32(f float32) *float32

Float32 provides a helper function to return a pointer to a float32

func Float64

func Float64(f float64) *float64

Float64 provides a helper function to return a pointer to a float64

func Int

func Int(i int) *int

Int provides a helper function to return a pointer to an int

func Int64

func Int64(i int64) *int64

Int64 provides a helper function to return a pointer to an int64

func Pointer

func Pointer[T any](v T) *T

Pointer provides a helper function to return a pointer to a type

func String

func String(s string) *string

String provides a helper function to return a pointer to a string

Types

type Accounts

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

func (*Accounts) Get

Get - Retrieve account details Retrieve the current account balance and other account details. You can also check the account limit and whether the account is a **main** account. Main accounts have unrestricted privileges and, via the [User Panel](https://panel.postivo.pl), you can create as many subaccounts as needed.

func (*Accounts) GetSubaccount

func (s *Accounts) GetSubaccount(ctx context.Context, userLogin string, opts ...operations.Option) (*operations.GetSubaccountDetailsResponse, error)

GetSubaccount - Get subaccount details Check the account balance and other details, such as the subcredit balance of a subaccount. Subaccounts are additional users who can access your account’s services and data. You can restrict access levels and set privileges for subaccounts in the [User Panel](https://panel.postivo.pl).

Provide the full subaccount login to access its data.

type AddressBook

type AddressBook struct {
	Contacts *Contacts
	Groups   *Groups
	// contains filtered or unexported fields
}

type ByExtID

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

func (*ByExtID) AddToGroup

func (s *ByExtID) AddToGroup(ctx context.Context, extID string, groupID int64, opts ...operations.Option) (*operations.AddContactByExtIDToGroupResponse, error)

AddToGroup - Add a contact to a group by EXT_ID Assign a contact to a group using the contact’s external (custom) ID (assigned when creating the contact). If a contact and a group exist in your account, you can add the contact to that group.

Provide the contact’s `ext_id` and the group’s `group_id` parameters to perform the assignment.

func (*ByExtID) Delete

Delete a contact by EXT_ID Remove a contact from your account by its external (custom) ID - the value defined when the contact was created.

func (*ByExtID) Get

Get - Retrieve contact details by EXT_ID Get the details of a contact from your Address Book using your external (custom) ID (the value you defined when creating the contact).

func (*ByExtID) RemoveFromGroup

func (s *ByExtID) RemoveFromGroup(ctx context.Context, extID string, groupID int64, opts ...operations.Option) (*operations.RemoveContactByExtIDToGroupResponse, error)

RemoveFromGroup - Remove a contact from a group by EXT_ID Remove a contact from a group in your Address Book using the contact’s external (custom) ID. This operation does not delete the contact; it only detaches the contact from the group. Provide the contact’s `ext_id` and the group’s `group_id` parameters to perform the detachment.

func (*ByExtID) Update

Update a contact by EXT_ID Update a contact by its external (custom) ID - the value you defined when creating the contact.

type Client

type Client struct {
	SDKVersion  string
	Accounts    *Accounts
	AddressBook *AddressBook
	Shipments   *Shipments
	Metadata    *Metadata
	// Common
	Common  *Common
	Senders *Senders
	// contains filtered or unexported fields
}

func New

func New(opts ...SDKOption) *Client

New creates a new instance of the SDK with the provided options

type Common

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

Common

func (*Common) Ping

func (s *Common) Ping(ctx context.Context, opts ...operations.Option) (*operations.PingResponse, error)

Ping - Check API availability and version Check the API connection and current availability status. The response also includes the current API version.

type Contacts

type Contacts struct {
	ByExtID *ByExtID
	// contains filtered or unexported fields
}

func (*Contacts) Add

Add a new contact Create a new contact in your account’s **Address Book**.

func (*Contacts) AddToGroup

func (s *Contacts) AddToGroup(ctx context.Context, id int64, groupID int64, opts ...operations.Option) (*operations.AddContactToGroupResponse, error)

AddToGroup - Add a contact to a group Assign a contact to a group. If a contact and a group exist in your account, you can add the contact to that group.

Provide the contact’s `id` and the group’s `group_id` parameters to perform the assignment.

func (*Contacts) Delete

Delete a contact Remove a contact from your account by system ID.

func (*Contacts) Get

Get - Retrieve contact details Get the details of a contact from your Address Book using its global `id`.

func (*Contacts) List

func (s *Contacts) List(ctx context.Context, page *int64, limit *int64, opts ...operations.Option) (*operations.ListContactsResponse, error)

List contacts Retrieve a paginated list of all contacts defined in your account’s **Address Book**.

func (*Contacts) RemoveFromGroup

func (s *Contacts) RemoveFromGroup(ctx context.Context, id int64, groupID int64, opts ...operations.Option) (*operations.RemoveContactFromGroupResponse, error)

RemoveFromGroup - Remove a contact from a group Remove a contact from a group in your Address Book. This does not delete the contact; it only detaches the contact from the group.

Provide the contact’s `id` and the group’s `group_id` parameters to perform the detachment.

func (*Contacts) Update

Update a contact Update a contact by its global ID.

type Groups

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

func (*Groups) Add

Add a new group Create a new contact group in your account’s Address Book.

func (*Groups) Delete

Delete a group Remove a group from your account’s Address Book by `ID`. Pass the group’s `id` to remove it. The group is deleted immediately from the Address Book.

If you also want to remove contacts that belong to this group, set the parameter `contacts` to `delete`. The default is `contacts: detach`, which detaches contacts from the removed group but leaves them in the Address Book.

func (*Groups) Get

Get - Retrieve group details Get the details of a single group from your Address Book by its `id` (returned when the group was created).

func (*Groups) List

List groups Retrieve the full list of groups defined in your account’s Address Book.

func (*Groups) Update

Update a group Update a group’s details by ID.

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient provides an interface for supplying the SDK with a custom HTTP client

type Metadata

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

func (*Metadata) GetPredefinedConfigs

func (s *Metadata) GetPredefinedConfigs(ctx context.Context, opts ...operations.Option) (*operations.ListPredefinedConfigsResponse, error)

GetPredefinedConfigs - List predefined configs Retrieve a complete list of predefined shipment configurations. The method has no body and takes no parameters. The response includes all stored configuration options.

func (*Metadata) List

List metadata Retrieve a complete list of all types for shipments and their possible values. The method has no body and takes no parameters. The response includes metadata such as carrier types, service types, and more.

type SDKOption

type SDKOption func(*Client)

func WithClient

func WithClient(client HTTPClient) SDKOption

WithClient allows the overriding of the default HTTP client used by the SDK

func WithRetryConfig

func WithRetryConfig(retryConfig retry.Config) SDKOption

func WithSecurity

func WithSecurity(bearer string) SDKOption

WithSecurity configures the SDK to use the provided security details

func WithSecuritySource

func WithSecuritySource(security func(context.Context) (components.Security, error)) SDKOption

WithSecuritySource configures the SDK to invoke the Security Source function on each method call to determine authentication

func WithServer

func WithServer(server string) SDKOption

WithServer allows the overriding of the default server by name

func WithServerURL

func WithServerURL(serverURL string) SDKOption

WithServerURL allows the overriding of the default server URL

func WithTemplatedServerURL

func WithTemplatedServerURL(serverURL string, params map[string]string) SDKOption

WithTemplatedServerURL allows the overriding of the default server URL with a templated URL populated with the provided parameters

func WithTimeout

func WithTimeout(timeout time.Duration) SDKOption

WithTimeout Optional request timeout applied to each operation

type Senders

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

func (*Senders) Add

Add a new sender Create a new sender on your account. The request must contain a `Sender` object. To prevent fraud, all additional senders are verified by mailing a verification code to the sender’s address. Complete the verification using the `verifySender` method. Verified senders have `active: true` and can be used to send shipments. Inactive senders are also returned (`active: false`), but cannot be used until verification is completed.

func (*Senders) Delete

Delete a sender Remove a sender from your account by `id`. Pass the sender’s `id` parameter to remove it. The sender is deleted immediately.

func (*Senders) List

List senders Retrieve the list of allowed senders defined in your account. Senders are registered in your account and must be verified and activated before use. Activated senders have `active: true` property and can be used to send shipments. Inactive senders are also returned (`active: false`), but cannot be used until activated.

func (*Senders) Verify

Verify sender Verify a sender to activate it. After adding a new sender, a letter containing a verification code is mailed to the sender’s address. Provide this code to complete verification.

type Shipments

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

func (*Shipments) Cancel

Cancel shipments Cancel shipments that have not yet been processed by their `ids`. Pass the unique shipment IDs (returned when the shipment was created) as a parameter. To cancel multiple shipments at once, provide a list of IDs (up to **50** per call). For larger volumes, split the operation into multiple requests. Only shipments with status `ACCEPTED` can be cancelled.

If duplicate shipment IDs are provided in a single call, the API processes each unique ID only once.

func (*Shipments) Dispatch

Dispatch a new shipment Send a shipment to one or multiple recipients in a single request. Provide a `Shipment` object. The object includes properties that define the shipment (recipient details, included documents, and optional settings). Some fields are required.

The system accepts up to **50** recipients per call. For larger volumes, split the operation into multiple requests.

func (*Shipments) Documents

Documents - Retrieve documents related to a shipment Download documents related to a shipment by its `id`. Pass the unique shipment `id` (returned when the shipment was created) as a parameter. The second parameter is the document type to download. Supported document types include: dispatch certificate, envelope template, and EPO (in PDF or XML formats).

func (*Shipments) Price

Price - Check the shipment price Check the price of a shipment for one or multiple recipients. Provide a `Shipment` object in the request. Each object includes properties such as recipient details, included documents, and optional settings. Some fields are required.

The system accepts up to **50** recipients per call. For larger volumes, split the operation into multiple requests.

func (*Shipments) Status

func (s *Shipments) Status(ctx context.Context, ids []string, opts ...operations.Option) (*operations.GetStatusResponse, error)

Status - Retrieve shipment details with status events Retrieve the current status and details for one or more shipments by their `ids`. Pass the unique shipment IDs (returned when the shipments were created) as a path parameter. To query provide a list (up to **50** IDs per call). For larger batches, split the requests.

Directories

Path Synopsis
internal
models

Jump to

Keyboard shortcuts

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