# Quickstart

Source: https://fragment.dev/guides/quickstart

[Documentation index](https://fragment.dev/llms.txt)

<a id="quickstart"></a>

<a id="overview"></a>

## Overview

To get started developing with Fragment:

1. Design your Schema
2. Generate an SDK
3. Deploy your Ledger
4. Integrate the API

Get started by [using the MCP](https://fragment.dev/markdown/guides/quickstart.md#use-the-mcp) or [following the guide](https://fragment.dev/markdown/guides/quickstart.md#follow-the-guide).

<a id="use-the-mcp"></a>

## Use the MCP

Open the [dashboard](https://dashboard.fragment.dev/go/mcp) and create a new MCP Connection. Paste the following prompt into your preferred AI tool:

Use the Fragment MCP to read the quickstart-mcp guide, then follow it end to end.

After this is done you'll have a script that demonstrates the integration against a Fragment Ledger.

- [Design a Schema](https://fragment.dev/markdown/guides/accounting-101.md) to fit your use-case
- Go to production by [embedding Fragment into your CI](https://fragment.dev/markdown/guides/embed-in-ci.md)
- [Migrate your existing ledger](https://fragment.dev/markdown/guides/import-data.md) to Fragment

<a id="follow-the-guide"></a>

## Follow the guide

<a id="follow-the-guide-design-your-schema"></a>

### Design your Schema

A Schema customizes a Fragment Ledger for a specific use-case. Download this toy Schema to begin the quickstart:

```json title=quickstart-schema.json expandable=true
{
  "key": "quickstart-schema",
  "chartOfAccounts": {
    "defaultConsistencyConfig": {
      "totalBalanceUpdates": "strong"
    },
    "defaultCurrencyMode": "multi",
    "accounts": [
      {
        "key": "assets",
        "type": "asset"
      },
      {
        "key": "liabilities",
        "type": "liability"
      },
      {
        "key": "income",
        "type": "income"
      },
      {
        "key": "expense",
        "type": "expense"
      }
    ]
  },
  "ledgerEntries": {
    "types": [
      {
        "type": "simple-entry",
        "lines": [
          {
            "key": "line-WPZ6bsw08YyW",
            "account": {
              "path": "assets"
            },
            "currency": {
              "code": "USD"
            },
            "amount": "{{gross_amount}}"
          },
          {
            "key": "line-m4spJaQWFqnw",
            "account": {
              "path": "liabilities"
            },
            "currency": {
              "code": "USD"
            },
            "amount": "{{gross_amount}}-{{fee_revenue}}"
          },
          {
            "key": "line-bvZiWSE69k4m",
            "account": {
              "path": "income"
            },
            "currency": {
              "code": "USD"
            },
            "amount": "{{fee_revenue}}"
          }
        ]
      }
    ]
  },
  "scenes": [
    {
      "name": "Simple Scenario",
      "events": [
        {
          "eventType": "entry",
          "entry": {
            "type": "simple-entry",
            "typeVersion": 1,
            "parameters": {
              "fee_revenue": "250",
              "gross_amount": "10000"
            }
          }
        }
      ]
    }
  ]
}
```

<a id="follow-the-guide-generate-an-sdk"></a>

### Generate an SDK

Generate a strongly-typed SDK specific to your Schema using the Fragment CLI.

1. Install the CLI via NPM or Homebrew:

   ```bash title="npm"
   npm install -g @fragment-dev/cli
   ```

   ```bash title="homebrew"
   brew tap fragment-dev/tap &&\
     brew install fragment-dev/tap/fragment-cli
   ```

2. Authenticate the CLI against your Fragment workspace:
   ```bash
   fragment login
   ```
3. Generate an SDK for your language:

   ```bash group="typescript"
   fragment gen-graphql \
     --path=quickstart-schema.jsonc \
     --output=queries.graphql &&\
   npm install --save @fragment-dev/node-client &&\
   npx fragment-node-client-codegen \
     --input=queries.graphql \
     --outputFilename=fragment-client.ts
   ```
```bash group="python"
   fragment gen-graphql \
     --path=quickstart-schema.jsonc \
     --output=queries.graphql &&\
   pip install fragment-python &&\
   fragment-python-client-codegen \
     --input-dir=. \
     --target-package-name=sdk \
     --output-dir=.
   ```
```bash group="go"
   fragment gen-graphql \
     --path=quickstart-schema.jsonc \
     --output=queries.graphql &&\
   go get 'github.com/fragment-dev/fragment-go/v3' &&\
   go run github.com/fragment-dev/fragment-go/v3 \
     --input=queries.graphql \
     --output=generated.go \
     --package=main
   ```
```bash group="ruby"
   fragment gen-graphql \
     --path=quickstart-schema.jsonc \
     --output=queries.graphql &&\
   gem install fragment-dev
   # The Ruby SDK reads queries.graphql at runtime,
   # so no code generation step is required.
   ```

4. Create an API client in the [dashboard](https://dashboard.fragment.dev/).
5. Initialize your Fragment client using the generated SDK and API client credentials:

   ```typescript title="quickstart.ts"
   import {
     createFragmentClient
   } from '@fragment-dev/node-client';
   import {
     getSdk
   } from './fragment-client';

   const fragment = createFragmentClient({
     params: {
       clientId: "<Client ID>",
       clientSecret: "<Client Secret>",
       apiUrl: "<API URL>",
       authUrl: "<OAuth URL>",
       scope: "<OAuth Scope>",
     },
     getSdk,
   });
   ```
```python title="quickstart.py"
   from .sdk.client import Client

   client = Client(
       client_id="<Client ID>",
       client_secret="<Client Secret>",
       api_url="<API URL>",
       auth_url="<OAuth URL>",
       auth_scope="<OAuth Scope>",
   )
   ```
```go title="quickstart.go"
   import (
     "github.com/fragment-dev/fragment-go/v3/client"
   )

   graphqlClient, err := client.NewClient(
     &client.GetTokenParams{
       ClientID:     "<Client ID>",
       ClientSecret: "<Client Secret>",
       Scope:        "<OAuth Scope>",
       AuthURL:      "<OAuth URL>",
       ApiURL:       "<API URL>",
     },
   )
   ```
```ruby title="quickstart.rb"
   require 'fragment_client'

   fragment = FragmentClient.new(
     "<Client ID>",
     "<Client Secret>",
     api_url: "<API URL>",
     oauth_url: "<OAuth URL>",
     oauth_scope: "<OAuth Scope>"
   )
   ```

<a id="follow-the-guide-deploy-your-ledger"></a>

### Deploy your Ledger

To deploy your Ledger:

1. Store the Schema
2. Create a Ledger from the Schema

```typescript title="quickstart.ts"
import { readFileSync } from 'node:fs';

// Load the Schema you downloaded with `fragment get-schema`.
const schema = JSON.parse(
  readFileSync('quickstart-schema.jsonc', 'utf8')
);

const { storeSchema } = await fragment.storeSchema({
  schema,
})

const { createLedger } = await fragment.createLedger({
  ik: `test-ledger`,
  ledger: {
    name: `quickstart ledger`,
  },
  schemaKey: schema.key,
})
```
```python title="quickstart.py"
import json

# Load the Schema you downloaded with `fragment get-schema`.
with open("quickstart-schema.jsonc") as f:
    schema = json.load(f)

await client.store_schema(schema=schema)

await client.create_ledger(
    ik="test-ledger",
    ledger={"name": "quickstart ledger"},
    schema_key=schema["key"],
)
```
```go title="quickstart.go"
import (
  "context"
  "encoding/json"
  "os"

  "github.com/fragment-dev/fragment-go/v3/queries"
)

// Load the Schema you downloaded with `fragment get-schema`.
data, _ := os.ReadFile("quickstart-schema.jsonc")
var schema queries.SchemaInput
json.Unmarshal(data, &schema)

queries.StoreSchema(context.Background(), graphqlClient, schema)

queries.CreateLedger(
  context.Background(),
  graphqlClient,
  "test-ledger",
  queries.CreateLedgerInput{Name: "quickstart ledger"},
  schema.Key,
)
```
```ruby title="quickstart.rb"
require 'json'

# Load the Schema you downloaded with `fragment get-schema`.
schema = JSON.parse(File.read('quickstart-schema.jsonc'))

fragment.store_schema({ schema: schema })

fragment.create_ledger({
  ik: 'test-ledger',
  ledger: { name: 'quickstart ledger' },
  schemaKey: schema['key']
})
```

<a id="follow-the-guide-integrate-the-api"></a>

### Integrate the API

Begin integrating the API into your product by:

1. Posting a Ledger Entry
2. Reading a Ledger Account's balance

```typescript title="quickstart.ts"
import { ReadBalanceConsistencyMode } from '@fragment-dev/node-client/types';
// Post the `simple-entry` Ledger Entry type
// with the required parameters
const { addLedgerEntry } = await fragment.PostSimpleEntry({
  ik: `quickstart-entry`,
  // The Ledger the Ledger Entry should post to.
  ledgerIk: `test-ledger`,
  gross_amount: '10000', // $100.00
  fee_revenue: '250', // $2.50
})

const { ledgerAccount } = await fragment.getLedgerAccountBalance({
  ledgerIk: `test-ledger`,
  path: `income`,
  balanceConsistencyMode: ReadBalanceConsistencyMode.Strong,
})

console.log(ledgerAccount.balance);
```
```python title="quickstart.py"
# Post the `simple-entry` Ledger Entry type
# with the required parameters
await client.post_simple_entry(
    ik="quickstart-entry",
    # The Ledger the Ledger Entry should post to.
    ledger_ik="test-ledger",
    gross_amount="10000",  # $100.00
    fee_revenue="250",  # $2.50
)

response = await client.get_ledger_account_balance(
    ledger_ik="test-ledger",
    path="income",
    balance_consistency_mode="strong",
)

print(response.ledger_account.balance)
```
```go title="quickstart.go"
// Post the `simple-entry` Ledger Entry type
// with the required parameters
queries.Post_SimpleEntry(
  context.Background(),
  graphqlClient,
  "quickstart-entry",
  // The Ledger the Ledger Entry should post to.
  "test-ledger",
  "10000", // gross_amount, $100.00
  "250",   // fee_revenue, $2.50
)

response, _ := queries.GetLedgerAccountBalance(
  context.Background(),
  graphqlClient,
  "income",
  "test-ledger",
  nil,
  nil,
  queries.ReadBalanceConsistencyModeStrong,
)

fmt.Println(response.LedgerAccount.Balance)
```
```ruby title="quickstart.rb"
# Post the `simple-entry` Ledger Entry type
# with the required parameters
fragment.post_simple_entry({
  ik: 'quickstart-entry',
  # The Ledger the Ledger Entry should post to.
  ledgerIk: 'test-ledger',
  gross_amount: '10000', # $100.00
  fee_revenue: '250' # $2.50
})

response = fragment.get_ledger_account_balance({
  ledgerIk: 'test-ledger',
  path: 'income',
  balanceConsistencyMode: 'strong'
})

puts response.data.ledger_account.balance
```

<a id="follow-the-guide-next-steps"></a>

### Next steps

- [Design a Schema](https://fragment.dev/markdown/guides/accounting-101.md) to fit your use-case
- Go to production by [embedding Fragment into your CI](https://fragment.dev/markdown/guides/embed-in-ci.md)
- [Migrate your existing ledger](https://fragment.dev/markdown/guides/import-data.md) to Fragment
