Custom API integration: send data from your own system

Modified on Thu, 26 Nov at 3:52 PM

Custom API integration: send data from your own system


A custom API integration lets your own systems, such as an ERP or a data warehouse, send spend and activity files to Position Green automatically. You set up the integration once in Data → Integrations. After that, your system uploads files through the API and follows how each one is processed.

You need a customer owner in Position Green to set it up, and a developer with an HTTPS client and a few dozen lines of code. No Azure account or SDK is needed.



How it works

A customer owner creates the integration in Position Green. This gives your system an API key (a client ID and secret) and a container in each organizational unit. A container is an upload template: it decides how the files are read, such as the column mapping and whether amounts include VAT.

Your system then sends every file through the same six steps:

  1. Get a token. Exchange the client ID and secret for a temporary access token.
  2. Pick the company. Ask which organizational units the API key may send data to.
  3. Ask for an upload link. Name the file you are about to send. You get a link for that one file and an import ID.
  4. Upload the file. Send the file to the link.
  5. Complete the upload. Tell Position Green the file is in place, so processing starts.
  6. Follow the import. Use the import ID to check the status and logs until the data is imported.

Set up the integration in Position Green

API connections are switched on per organization. If you do not see the options below, ask your Position Green contact to switch them on.

1. Add a custom integration

  1. Go to Data → Integrations and select Add integration.
  2. Select Create your own integration.

The Add integration window. Create your own integration is for systems that do not have a standard integration.

2. Create the API key

Select Create your API key. If your organization already has an API connection, you can use it instead.

Fill in the new API connection:

  • Name and Description: what the connection is for, such as "ERP export".
  • Contact email: who to contact when uploads fail or the secret is about to expire. You can change it later.
  • Secret expires on: leave it empty for the longest allowed, 24 months.
  • API key allowances: for each organizational unit, choose what the key may do there. Write uploads files and reads imports, and is needed to upload. Read only reads imports and their logs.

Select Create API connection.

A new API connection with Write and Read on five organizational units.

3. Copy the client ID and secret

Copy the client ID and client secret and give them to your developers in a safe way. The secret is shown only once. If it is lost, add a new secret in the connection's details.

The credentials are shown once. Store the secret like a password, for example in a secrets manager.

4. Choose the data type and create the integration

Choose what the integration will send:

  • Financial accounting: spend from your accounting, such as purchases and other transactions.
  • Activity data: consumption data, such as energy, fuel or travel.

Position Green shows the containers it will create: one for each organizational unit the key can write to. Select Create integration.

Each organizational unit gets its own container, named after the API connection and the data type.

The last window sums up what to share with your developers: the API connection, the client ID and the data type. Your developers never need container IDs. They name the company, and Position Green finds the right container.

5. Check the containers

Each container shows as a card under Data → Integrations, marked Waiting for data until its first file arrives. If the API key later gets Write on another organizational unit, that unit gets containers for the data types the key already sends.

Five new ERP export containers, waiting for their first file.

6. Set how the files are read

How a file is read is set once on the container, not with every upload. Open a container and select Template settings to set whether amounts include VAT and to map your file's columns. Under Account settings you set the accounting standard.

Template settings: the VAT setting and the column mapping for the container.

  • A new container starts with the default column mapping for its data type.
  • The first file that is processed without failing gives the container its example row. It is shown next to the mapping fields, so you can see which of your columns holds what.
  • Later files are imported with the container's current mapping. It changes only when someone edits it.

So make your first file a typical one, with your real column names and a representative first row.

For developers: send files through the API

APIhttps://api-carbon.positiongreen.com
Uploadshttps://upload.api-carbon.positiongreen.com
Test environment (on request)https://api-carbon-test.positiongreen.com and https://upload.api-carbon-test.positiongreen.com
Sign-inOAuth 2.0 client credentials
QueriesGraphQL, POST /graphql/client
File types.csv, .xlsx (first sheet), .zip
File sizeUp to 5000 MiB per file
Upload linkOne file; valid for 6 hours

Your system needs outgoing HTTPS (port 443) to the API host and the upload host. Nothing needs to reach your system.

Step 1: Get a token

Send the client ID and secret form-encoded to POST /auth/client-api/token:

curl -s -X POST https://api-carbon.positiongreen.com/auth/client-api/token \
  -d grant_type=client_credentials \
  -d client_id="$PG_CLIENT_ID" \
  -d client_secret="$PG_CLIENT_SECRET"

The response holds the token and how many seconds it lasts, usually about an hour:

{ "access_token": "eyJ0eXAiOiJKV1Qi…", "token_type": "Bearer", "expires_in": 3599 }

Reuse the token until it is about a minute from expiring. Do not request a token for every call: token requests are limited per hour.

Step 2: Pick the company

Everything else is GraphQL. Send a JSON body with query and variables to POST /graphql/client, with the header Authorization: Bearer <token>. A request that is refused still returns HTTP 200, with the reason in an errors list, so always check for it.

query {
  me { displayName }
  companies { id name }
}

Pass a company's id as companyId in the next steps. Company IDs do not change, so you can keep them in your configuration.

Step 3: Ask for an upload link

mutation RequestUpload($input: RequestUploadInput!) {
  requestUpload(input: $input) {
    dataImport { id status }
    uploadLink { url method headers { name value } expiresAt }
  }
}

Variables:

{ "input": { "companyId": "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed", "fileName": "spend-2026-q3.xlsx" } }
  • fileName must end in .csv, .xlsx or .zip. To send a CSV compressed, put it in a .zip.
  • Pass dataType (FINANCIAL or ACTIVITY) only if the API key has both kinds of integration for the company.
  • The company needs a country in Position Green. Without one, no link is issued.
  • Keep dataImport.id. You need it in steps 5 and 6.
  • Ask for a new link for every file.

Step 4: Upload the file

Send the file with one HTTPS PUT to uploadLink.url, with the headers from uploadLink.headers. Use the link exactly as returned.

curl --fail -X PUT \
  -H "x-ms-blob-type: BlockBlob" \
  --upload-file spend-2026-q3.xlsx \
  "$UPLOAD_URL"
  • 201 Created means the file is stored.
  • Send the length up front (Content-Length). Uploads without a length are refused.
  • Do not put a short timeout on the upload. A large file over a slow line can take more than an hour.
  • The Azure Storage SDKs are optional. They can send big files in parallel parts with automatic retries, using the same link.

Step 5: Complete the upload

Tell Position Green the file is in place. Nothing is processed until you do this.

mutation CompleteUpload($input: CompleteUploadInput!) {
  completeUpload(input: $input) { dataImport { id status } }
}

Variables: { "input": { "companyId": "…", "dataImportId": "…" } }. The import is now IN_PROGRESS. Complete the upload within 8 hours of asking for the link. Calling it again is safe.

Step 6: Follow the import

Ask for the status every 30 to 60 seconds until the import is finished:

query Import($companyId: UUID!, $id: UUID!) {
  dataImport(companyId: $companyId, id: $id) {
    status
    errorMessage
    logs { createdAt level message }
  }
}
StatusWhat it means
AWAITING_FILEThe link is issued. Waiting for the file and the completeUpload call.
IN_PROGRESSThe file is being processed. Large files can take several minutes.
COMPLETEDDone. The data is in Position Green.
FAILEDRead errorMessage and logs, fix the file and send it again with a new link.
DELETEDSomeone removed the import in Position Green.

To list earlier imports, use the dataImports(companyId, limit, offset) query. To see which fields your files can hold, use the dataFields(dataType) query.

Explore the schema

Open https://api-carbon.positiongreen.com/graphql/client in a browser for an interactive explorer. Add your token in the Headers tab as {"Authorization": "Bearer <token>"}, then open Docs to browse every query and field. Queries run against real data, so try uploads in the test environment first.

Full example in Python

One script that uploads a file and waits for the result. Set PG_CLIENT_ID, PG_CLIENT_SECRET and PG_COMPANY_ID, and pass the file path. Set PG_DATA_TYPE too if the API key has both kinds of integration for the company.

"""Upload one file to Position Green and wait until it is imported.

pip install requests
PG_CLIENT_ID=… PG_CLIENT_SECRET=… PG_COMPANY_ID=… python pg_upload.py spend-2026-q3.xlsx
"""
import os
import sys
import time

import requests

API = "https://api-carbon.positiongreen.com"
_token = {"value": "", "expires": 0.0}

REQUEST_UPLOAD = """
mutation ($input: RequestUploadInput!) {
  requestUpload(input: $input) {
    dataImport { id }
    uploadLink { url method headers { name value } }
  }
}"""

COMPLETE = """
mutation ($input: CompleteUploadInput!) {
  completeUpload(input: $input) { dataImport { id status } }
}"""

IMPORT = """
query ($c: UUID!, $d: UUID!) {
  dataImport(companyId: $c, id: $d) {
    status errorMessage logs { createdAt level message }
  }
}"""


def get_token() -> str:
    if time.time() < _token["expires"] - 60:
        return _token["value"]
    r = requests.post(f"{API}/auth/client-api/token", data={
        "grant_type": "client_credentials",
        "client_id": os.environ["PG_CLIENT_ID"],
        "client_secret": os.environ["PG_CLIENT_SECRET"],
    }, timeout=30)
    r.raise_for_status()
    body = r.json()
    _token.update(value=body["access_token"], expires=time.time() + body["expires_in"])
    return _token["value"]


def graphql(query: str, variables: dict) -> dict:
    r = requests.post(f"{API}/graphql/client", json={"query": query, "variables": variables},
                      headers={"Authorization": f"Bearer {get_token()}"}, timeout=60)
    r.raise_for_status()
    body = r.json()
    if body.get("errors"):
        raise RuntimeError(body["errors"][0]["message"])
    return body["data"]


def main(path: str) -> None:
    company = os.environ["PG_COMPANY_ID"]
    upload = graphql(REQUEST_UPLOAD, {"input": {
        "companyId": company,
        "fileName": os.path.basename(path),
        "dataType": os.environ.get("PG_DATA_TYPE"),
    }})["requestUpload"]
    data_import_id = upload["dataImport"]["id"]
    link = upload["uploadLink"]

    headers = {h["name"]: h["value"] for h in link["headers"]}
    with open(path, "rb") as f:
        requests.request(link["method"], link["url"], data=f, headers=headers,
                         timeout=(30, None)).raise_for_status()
    graphql(COMPLETE, {"input": {"companyId": company, "dataImportId": data_import_id}})
    print("Uploaded and completed. Import", data_import_id)

    while True:
        time.sleep(30)
        result = graphql(IMPORT, {"c": company, "d": data_import_id})["dataImport"]
        if result["status"] in ("COMPLETED", "FAILED", "DELETED"):
            for entry in result["logs"]:
                print(entry["createdAt"], entry["level"], entry["message"])
            if result["status"] != "COMPLETED":
                sys.exit(result["errorMessage"] or result["status"])
            print("Imported.")
            return


if __name__ == "__main__":
    main(sys.argv[1])

Rate limits

WhatLimitOver the limit
GraphQL, POST /graphql/client120 calls a minute per API connectionHTTP 429, RATE_LIMITED, Retry-After: 60
Token, POST /auth/client-api/token300 requests an hour per IP address, and 60 an hour per client IDHTTP 429, RATE_LIMITED, Retry-After: 3600

After a 429, wait the number of seconds in Retry-After before you try again.

Common errors

ErrorWhat to do
Token: HTTP 401, INVALID_CLIENT_CREDENTIALSThe client ID or secret is wrong, the secret has expired, or the API connection was revoked. Ask your customer owner for a new secret.
GraphQL: HTTP 401, TOKEN_EXPIREDGet a new token and repeat the call.
GraphQL: INSUFFICIENT_PERMISSIONS or ACCESS_DENIEDThe API key lacks Write (to upload) or Read (to read imports) on that company. Ask your customer owner.
requestUpload: "This API connection has no integration for <company>"Create an integration for that company in Data → Integrations.
requestUpload: pass dataTypeThe key has both a financial and an activity integration for the company. Pass dataType.
requestUpload: COMPANY_COUNTRY_REQUIREDSet the company's country in Position Green, then ask for a link again.
completeUpload: "No file has arrived yet"Upload the file again with the same link while it is valid, then call completeUpload again.
Upload: HTTP 403The link expired before the upload started. Ask for a new link.
Upload: HTTP 413The file is larger than 5000 MiB.

Manage your API connections

Customer owners see every API connection under Settings → API connections, with its client ID, the organizational units it may use and when its secret expires. Select a connection to add or remove a secret, change its organizational units or contact email, or revoke it.

Rotate a secret without downtime. A secret is valid for up to 24 months. An API connection can have two secrets at a time: add a second secret, switch your system to it, then remove the old one.

Data retention and deletion

  • Every file you upload becomes a data import with its own ID, which ties the file to every row it brought in.
  • Uploaded files and their data are kept for as long as you are a customer. How long they are kept after your agreement ends is set in your data processing agreement (DPA).
  • Someone with the Editor role can delete an import in Position Green. Its data is excluded from your figures straight away. To have an import removed permanently, ask your Position Green contact.
  • An import that is not completed within 8 hours is marked FAILED and holds no data.

Moving from the earlier API

If your system uses the earlier upload API (api.morescope.com, /client/upload), this is where each part moved:

Earlier APIThis API
Base URL https://api.morescope.comhttps://api-carbon.positiongreen.com
Credentials requested from supportAn API connection a customer owner creates in Data → Integrations
POST /auth/client-tokenPOST /auth/client-api/token, same form fields
GET /client/authorized-companies, external_company_idThe companies query, id
POST /client/upload with the file in the requestrequestUpload, a PUT of the file, then completeUpload
is_vat_included, account_standard and year with every uploadNot sent. The container's settings in Position Green decide how the file is read.
upload_identifierdataImport.id
GET /client/upload/{upload_identifier}/logsThe dataImport query: status, errorMessage and logs

Questions about your integration? Contact your Position Green customer success manager or support@positiongreen.com.

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article