# getLedgers

> For the complete documentation index, see [llms.txt](/docs/llms.txt).

POST https://stellar-mainnet.g.alchemy.com/v2/{apiKey}

The `getLedgers` method returns a detailed list of ledgers starting from the user specified starting point that you can paginate as long as the pages fall within the history retention of their corresponding RPC provider.

Reference: https://www.alchemy.com/docs/chains/stellar/stellar-api-endpoints/get-ledgers

## Parameters

| Name | Type | Required | Description |
|------|------|----------|-------------|
| startLedger | number | No | Ledger sequence number to start fetching responses from (inclusive). This method will return an error if `startLedger` is less than the oldest ledger stored in this node, or greater than the latest ledger seen by this node. If a cursor is included in the request, `startLedger` must be omitted. |
| pagination | object | No | Pagination in stellar-rpc is similar to pagination in Horizon. See [Pagination](https://developers.stellar.org/docs/data/rpc/api-reference/structure/pagination). |
| xdrFormat | string | No | Lets the user choose the format in which the response should be returned - either as unpacked JSON or as base64-encoded XDR strings. Note that you should not rely on any schema for the JSON, as it will change when the underlying XDR changes. |

## Result

**getLedgersResult** (object)

## Code Examples

### cURL

```bash
curl --request POST \
  --url https://stellar-mainnet.g.alchemy.com/v2/docs-demo \
  --header 'Content-Type: application/json' \
  --data '{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "getLedgers",
  "params": [
    1,
    {
      "cursor": "string",
      "limit": 1
    },
    "string"
  ]
}'
```

### JavaScript

```javascript
const options = {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({
    jsonrpc: '2.0',
    id: 1,
    method: 'getLedgers',
    params: [1, {cursor: 'string', limit: 1}, 'string']
  })
};

fetch('https://stellar-mainnet.g.alchemy.com/v2/docs-demo', options)
  .then(res => res.json())
  .then(res => console.log(res))
  .catch(err => console.error(err));
```

### Python

```python
import requests

url = "https://stellar-mainnet.g.alchemy.com/v2/docs-demo"

payload = {
    "jsonrpc": "2.0",
    "id": 1,
    "method": "getLedgers",
    "params": [
        1,
        {
            "cursor": "string",
            "limit": 1
        },
        "string"
    ]
}
headers = {"Content-Type": "application/json"}

response = requests.post(url, json=payload, headers=headers)

print(response.text)
```

### Go

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://stellar-mainnet.g.alchemy.com/v2/docs-demo"

	payload := strings.NewReader("{\n  \"jsonrpc\": \"2.0\",\n  \"id\": 1,\n  \"method\": \"getLedgers\",\n  \"params\": [\n    1,\n    {\n      \"cursor\": \"string\",\n      \"limit\": 1\n    },\n    \"string\"\n  ]\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(string(body))

}
```

### Java

```java
HttpResponse<String> response = Unirest.post("https://stellar-mainnet.g.alchemy.com/v2/docs-demo")
  .header("Content-Type", "application/json")
  .body("{\n  \"jsonrpc\": \"2.0\",\n  \"id\": 1,\n  \"method\": \"getLedgers\",\n  \"params\": [\n    1,\n    {\n      \"cursor\": \"string\",\n      \"limit\": 1\n    },\n    \"string\"\n  ]\n}")
  .asString();
```

### C#

```csharp
using RestSharp;


var options = new RestClientOptions("https://stellar-mainnet.g.alchemy.com/v2/docs-demo");
var client = new RestClient(options);
var request = new RestRequest("");
request.AddJsonBody("{\n  \"jsonrpc\": \"2.0\",\n  \"id\": 1,\n  \"method\": \"getLedgers\",\n  \"params\": [\n    1,\n    {\n      \"cursor\": \"string\",\n      \"limit\": 1\n    },\n    \"string\"\n  ]\n}", false);
var response = await client.PostAsync(request);

Console.WriteLine("{0}", response.Content);

```


## OpenRPC Method Specification

```yaml
name: getLedgers
summary: returns a list of ledgers with their details
description: The `getLedgers` method returns a detailed list of ledgers starting from the user specified starting point that you can paginate as long as the pages fall within the history retention of their corresponding RPC provider.
externalDocs:
  url: https://developers.stellar.org/docs/data/apis/rpc/api-reference/methods/getLedgers
paramStructure: by-name
params:
  - name: startLedger
    summary: ledger to begin searching from
    description: Ledger sequence number to start fetching responses from (inclusive). This method will return an error if `startLedger` is less than the oldest ledger stored in this node, or greater than the latest ledger seen by this node. If a cursor is included in the request, `startLedger` must be omitted.
    required: false
    schema:
      title: ledgerSequence
      description: Sequence number of the ledger.
      type: number
  - name: pagination
    summary: pagination options
    description: Pagination in stellar-rpc is similar to pagination in Horizon. See [Pagination](https://developers.stellar.org/docs/data/rpc/api-reference/structure/pagination).
    required: false
    schema:
      type: object
      required: []
      properties:
        cursor:
          type: string
          description: An opaque string which acts as a paging token. To obtain the next page of results occurring after a given response set this value to the `cursor` field of the response.
        limit:
          type: number
          description: The maximum number of records returned. The limit for getEvents can range from 1 to 10000 - an upper limit that is hardcoded in Stellar-RPC for performance reasons. If this argument isn't designated, it defaults to 100.
  - name: xdrFormat
    summary: 'chooses a response format for XDR fields: ''json'' or ''base64'''
    required: false
    description: Lets the user choose the format in which the response should be returned - either as unpacked JSON or as base64-encoded XDR strings. Note that you should not rely on any schema for the JSON, as it will change when the underlying XDR changes.
    schema:
      title: xdrFormat
      type: string
      description: Specifies whether XDR should be encoded as Base64 (default or 'base64') or JSON ('json').
result:
  name: getLedgersResult
  schema:
    type: object
    properties:
      ledgers:
        type: array
        items:
          type: object
          properties:
            hash:
              type: string
              description: The hash of the ledger header which was included in the chain
            sequence:
              title: ledgerSequence
              description: The sequence number of the ledger (sometimes called the 'block height').
              type: number
            ledgerCloseTime:
              title: ledgerCloseTime
              description: The timestamp at which the ledger was closed.
              type: string
            headerXdr:
              type: string
              description: The [LedgerHeader](https://github.com/stellar/stellar-xdr/blob/v22.0/Stellar-ledger.x#L74) structure for this ledger (base64-encoded string).
            metadataXdr:
              type: string
              description: The [LedgerCloseMeta](https://github.com/stellar/stellar-xdr/blob/v22.0/Stellar-ledger.x#L539) union for this ledger (base64-encoded string).
      latestLedger:
        title: latestLedger
        description: The sequence number of the latest ledger known to Stellar RPC at the time it handled the request.
        type: number
      latestLedgerCloseTime:
        title: latestLedgerCloseTime
        description: The unix timestamp of the close time of the latest ledger known to Stellar RPC at the time it handled the request.
        type: number
      oldestLedger:
        title: oldestLedger
        description: The sequence number of the oldest ledger ingested by Stellar RPC at the time it handled the request.
        type: number
      oldestLedgerCloseTime:
        title: oldestLedgerCloseTime
        description: The unix timestamp of the close time of the oldest ledger ingested by Stellar RPC at the time it handled the request.
        type: number
      cursor:
        title: cursor
        type: string
        description: A token which can be included in a subsequent request to obtain the next page of results.
```
