Skip to content

04 Paginated responses

Victor Hugo Avelar Ossorio edited this page Mar 1, 2024 · 1 revision

Handling paginated responses

Mollie's API endpoints offer pagination support when fetching lists of resources. To manage this, you can follow the approach outlined below:

Let's say we have a total of 1000 registered payments and we want to retrieve all of them. The API allows a maximum of 250 elements per page. If we utilize this maximum value, we would need to navigate through 4 pages to access all the payment records.

package main

import (
 "context"
 "log"

 "github.com/VictorAvelar/mollie-api-go/v3/mollie"
 "github.com/VictorAvelar/mollie-api-go/v3/mollie/tools/pagination"
)

func main() {
 config := mollie.NewAPITestingConfig(true)

 client, err := mollie.NewClient(nil, config)
 if err != nil {
  panic(err)
 }

 ctx := context.Background()

 _, cp, err := client.Payments.List(ctx, &mollie.ListPaymentOptions{Limit: 250})
 if err != nil {
  panic(err)
 }

 var payments []mollie.Payment

 // Runs until the next page pointer is empty.
 for cp.Links.Next != nil {
  payments = append(payments, cp.Embedded.Payments...)
  // We extract the pointer from which the next page starts.
  ptr, err := pagination.ExtractFromQueryParam(cp.Links.Next.Href)
  if err != nil {
   panic(err)
  }

  _, cp, err = client.Payments.List(ctx, &mollie.ListPaymentOptions{From: ptr, Limit: 250})
  if err != nil {
   panic(err)
  }
 }

 log.Printf("total payments: %v", len(payments))
 // Expect: 1000
}
Clone this wiki locally