SAP Business One Service Layer: Integrate External Systems with the REST API - tutorial featured image

Publications

SAP Business One Service Layer: Integrate External Systems with the REST API

Hector Pincheira

Hector Pincheira

CIO | CTO
Digital Strategy & Technology Innovation

items

If your company already has an e-commerce, a field sales app, or a WMS that needs to talk to the ERP, the SAP Business One Service Layer It is likely the missing piece you need. It is SAP's official REST interface for reading and writing data in SAP Business One without touching the database directly. However, most companies still integrate systems with manual SQL inserts, flat files, or nightly routines that no one audits. The result is predictable: corrupted documents, broken numbering, and accounting that stops balancing.

In this tutorial, we are going to walk the complete path. First, you will understand what the Service Layer solves and what it does not. Then, you will set up a functional integration step by step. Finally, and this is what almost nobody does, you will set up the auditing SQL queries that let you sleep peacefully knowing what your integration is writing to the ERP.

SAP Business One Service Layer - server infrastructure supporting the ERP's REST integrations
The Service Layer runs as an independent service on your SAP Business One server.

What is the SAP Business One Service Layer and Why You Need It

The Service Layer is an application server that exposes SAP Business One business objects as REST services under the OData protocol. In other words, each object you know from the user interface (business partner, item, sales order, invoice, delivery) has its equivalent as an HTTP endpoint. As of Feature Pack 2405, OData v3 has been deprecated and OData v4 is the main protocol, with nearly 500 services and more than 1,900 endpoints available.

The difference compared to a direct SQL insertion is substantial. When you write to the ORDR table with an INSERT, you are bypassing all the ERP's business logic: stock validations, determination of general ledger accounts, numbering series, taxes, exchange rates, and authorization triggers. The Service Layer, on the other hand, executes the exact same logic that a user would execute when saving the document on the screen. Therefore, what enters through the Service Layer is valid from an accounting perspective by construction.

Furthermore, there is a supporting argument that is worth keeping in mind in any conversation with your partner: SAP does not support databases with direct writes. If an auditor or a consultant detects manual INSERTs in system tables, your installation is no longer supported. Consequently, the Service Layer is not only the technically correct option, but the only defensible one in the face of an audit.

When NOT to use the Service Layer

Now let's be honest: the Service Layer is not the answer for everything. If you need to read a million records to feed a BI dashboard, a read-only SQL view will be orders of magnitude faster. Similarly, if you are going to load master catalogs just once during an implementation, the Data Transfer Workbench is still more practical. The Service Layer shines in real-time, transactional operations with business logic: creating an order from an e-commerce platform, registering a payment, updating a business partner.

Prerequisites before starting

  • SAP Business One 9.3 or higher (recommended 10.0 FP2405 or later for full OData v4).
  • Service Layer installed and running. On SAP HANA installations it comes by default; on SQL Server it must be enabled from the server installer.
  • Port 50000 (HTTPS) accessible from the system that will be integrated. Check the firewall before blaming the ERP.
  • A dedicated SAP user to the integration, with an assigned license and restricted permissions. Never use the manager user.
  • Database access in read-only mode to execute the audit queries from the final section.
  • SSL Certificate Resolved. The Service Layer brings a self-signed one; in production replace it with a valid one.

Step-by-step tutorial: your first integration

Step 1: Verify that the service responds

Before writing a single line of code, confirm that the Service Layer is alive. From the server's browser, access the metadata URL. If you get a huge XML document with the definition of all entities, the service is operational.

GET https://TU_SERVIDOR:50000/b1s/v2/$metadata

If the browser complains about the certificate, accept it temporarily. If, on the other hand, it does not respond at all, check the «SAP Business One Service Layer» service in Windows Services or the container status in Linux.

Step 2: Authenticate and obtain the session

Every operation requires an active session. Login is performed with a POST request that sends the company database, username, and password. The response includes a B1SESSION cookie that you must send with each subsequent call. By default, that session expires after 30 minutes of inactivity, a value that can be configured in the b1s.conf file or from the SLD Control Center.

POST https://YOUR_SERVER:50000/b1s/v2/Login
Content-Type: application/json
{
  "CompanyDB": "SBODEMOCL",
  "UserName": "integration",
  "Password": "YourSecurePassword"
}

The response returns a B1Session object with the SessionId. Save that identifier and reuse it. A classic mistake made by teams just starting out is to log in on every call, which consumes license connections and ends up saturating the server.

Step 3: Query data with OData filters

With the session active, you can now read. OData allows you to filter, select fields, and sort directly in the URL, which dramatically reduces the transferred volume. For example, to fetch only active articles with available stock:

GET /b1s/v2/Items?$select=ItemCode,ItemName,QuantityOnStock
    &$filter=Valid eq 'tYES' and QuantityOnStock gt 0
    &$orderby=ItemName
    &$top=50
Cookie: B1SESSION=xxxxxxxx

For larger volumes, use pagination with the Prefer: odata.maxpagesize parameter. Also, avoid fetching entire entities when you only need three fields: the $select parameter is your best ally for performance.

Step 4: Create a document with all the business logic

This is where the Service Layer justifies its existence. Creating a sales order involves a POST to the Orders collection with the header and lines. SAP takes care of the rest: numbering, taxes, account determination, and validations.

POST /b1s/v2/Orders
Cookie: B1SESSION=xxxxxxxx
Content-Type: application/json
{
  "CardCode": "C20000",
  "DocDate": "2026-08-21",
  "DocDueDate": "2026-08-28",
  "NumAtCard": "ECOM-2026-004512",
  "Comments": "Order generated from e-commerce",
  "DocumentLines": [
    { "ItemCode": "A00001", "Quantity": 5, "WarehouseCode": "01" },
    { "ItemCode": "A00002", "Quantity": 2, "WarehouseCode": "01" }
  ]
}

Pay special attention to the field NumAtCard. There you must write the unique identifier of the source system. As a result, you will have a reconciliation key between both worlds and you will be able to detect duplicates, which is precisely what we will do with SQL later.

Step 5: Log out

When the process is finished, log out with a POST to /Logout. This way, you release the license connection immediately instead of waiting for the 30-minute expiration. In high-volume integrations, this simple discipline avoids the dreaded «maximum connections reached» error in the middle of the afternoon.

SAP Business One Service Layer - REST integration development and code monitoring
Each call to the Service Layer executes the same business logic as a user on screen.

SQL queries to audit your integration

An integration without an audit is a black box. Therefore, these three queries should live in your Query Manager from day one. All of them are in SQL Server and SAP HANA versions.

What is your integration user writing

This query shows the volume of documents created by the integration user over the last 30 days, grouped by document type. It is your first indicator that something changed in behavior.

SQL Server

-- Volume of documents created by the integration user (last 30 days)
SELECT 'Sales Orders' AS Document, CONVERT(DATE, T0.CreateDate) AS Date,
       COUNT(*) AS Quantity, SUM(T0.DocTotal) AS TotalAmount
FROM ORDR T0 WITH (NOLOCK)
INNER JOIN OUSR T1 WITH (NOLOCK) ON T0.UserSign = T1.USERID
WHERE T1.U_NAME = 'integracion'
  AND T0.CreateDate >= DATEADD(DAY, -30, GETDATE())
GROUP BY CONVERT(DATE, T0.CreateDate)
UNION ALL
SELECT 'Sales Invoices', CONVERT(DATE, T0.CreateDate),
       COUNT(*), SUM(T0.DocTotal)
FROM OINV T0 WITH (NOLOCK)
INNER JOIN OUSR T1 WITH (NOLOCK) ON T0.UserSign = T1.USERID
WHERE T1.U_NAME = 'integracion'
  AND T0.CreateDate >= DATEADD(DAY, -30, GETDATE())
GROUP BY CONVERT(DATE, T0.CreateDate)
ORDER BY Date DESC, Document;

SAP HANA

-- Volume of documents created by the integration user (last 30 days)
SELECT 'Sales Orders' AS "Document", TO_DATE(T0."CreateDate") AS "Date",
       COUNT(*) AS "Quantity", SUM(T0."DocTotal") AS "TotalAmount"
FROM ORDR T0
INNER JOIN OUSR T1 ON T0."UserSign" = T1."USERID"
WHERE T1."U_NAME" = 'integracion'
  AND T0."CreateDate" >= ADD_DAYS(CURRENT_DATE, -30)
GROUP BY TO_DATE(T0."CreateDate")
UNION ALL
SELECT 'Sales Invoices', TO_DATE(T0."CreateDate"),
       COUNT(*), SUM(T0."DocTotal")
FROM OINV T0
INNER JOIN OUSR T1 ON T0."UserSign" = T1."USERID"
WHERE T1."U_NAME" = 'integracion'
  AND T0."CreateDate" >= ADD_DAYS(CURRENT_DATE, -30)
GROUP BY TO_DATE(T0."CreateDate")
ORDER BY "Date" DESC, "Document";

Query 2: Detect duplicate documents by external reference

This is the most expensive integration error: a network timeout causes the source system to retry and you end up with two identical orders. If you respected the use of NumAtCard, detecting them is trivial.

SQL Server

-- Pedidos duplicados por referencia externa (NumAtCard)
SELECT T0.NumAtCard AS RefExterna, COUNT(*) AS Repeticiones,
       MIN(T0.DocNum) AS PrimerDoc, MAX(T0.DocNum) AS UltimoDoc,
       MAX(T0.CardCode) AS Cliente, SUM(T0.DocTotal) AS MontoDuplicado,
       DATEDIFF(MINUTE, MIN(T0.CreateDate), MAX(T0.CreateDate)) AS MinutosEntreDocs
FROM ORDR T0 WITH (NOLOCK)
WHERE ISNULL(T0.NumAtCard, '') <> ''
  AND T0.CreateDate >= DATEADD(MONTH, -3, GETDATE())
  AND T0.CANCELED = 'N'
GROUP BY T0.NumAtCard
HAVING COUNT(*) > 1
ORDER BY Repeticiones DESC, MontoDuplicado DESC;

SAP HANA

-- Pedidos duplicados por referencia externa (NumAtCard)
SELECT T0."NumAtCard" AS "RefExterna", COUNT(*) AS "Repeticiones",
       MIN(T0."DocNum") AS "PrimerDoc", MAX(T0."DocNum") AS "UltimoDoc",
       MAX(T0."CardCode") AS "Cliente", SUM(T0."DocTotal") AS "MontoDuplicado",
       SECONDS_BETWEEN(MIN(T0."CreateDate"), MAX(T0."CreateDate")) / 60 AS "MinutosEntreDocs"
FROM ORDR T0
WHERE IFNULL(T0."NumAtCard", '') <> ''
  AND T0."CreateDate" >= ADD_MONTHS(CURRENT_DATE, -3)
  AND T0."CANCELED" = 'N'
GROUP BY T0."NumAtCard"
HAVING COUNT(*) > 1
ORDER BY "Repeticiones" DESC, "MontoDuplicado" DESC;

Query 3: Integrated orders that never advanced

An order created by the integration that has gone days without delivery or an invoice usually indicates a data issue: a blocked customer, nonexistent stock, or a zero price. This query exposes them before the customer does by phone.

SQL Server

-- Pedidos integrados abiertos y estancados
SELECT T0.DocNum, T0.NumAtCard AS RefExterna, T0.CardCode,
       T0.CardName, T0.DocDate, T0.DocTotal,
       DATEDIFF(DAY, T0.DocDate, GETDATE()) AS DiasAbierto,
       CASE WHEN T0.DocTotal = 0 THEN 'Total en cero'
            WHEN T1.frozenFor = 'Y' THEN 'Cliente bloqueado'
            ELSE 'Revisar stock o autorizacion' END AS PosibleCausa
FROM ORDR T0 WITH (NOLOCK)
INNER JOIN OCRD T1 WITH (NOLOCK) ON T0.CardCode = T1.CardCode
WHERE T0.DocStatus = 'O'
  AND T0.CANCELED = 'N'
  AND ISNULL(T0.NumAtCard, '') <> ''
  AND DATEDIFF(DAY, T0.DocDate, GETDATE()) > 5
ORDER BY DiasAbierto DESC;

SAP HANA

-- Pedidos integrados abiertos y estancados
SELECT T0."DocNum", T0."NumAtCard" AS "RefExterna", T0."CardCode",
       T0."CardName", T0."DocDate", T0."DocTotal",
       DAYS_BETWEEN(T0."DocDate", CURRENT_DATE) AS "DiasAbierto",
       CASE WHEN T0."DocTotal" = 0 THEN 'Total en cero'
            WHEN T1."frozenFor" = 'Y' THEN 'Cliente bloqueado'
            ELSE 'Revisar stock o autorizacion' END AS "PosibleCausa"
FROM ORDR T0
INNER JOIN OCRD T1 ON T0."CardCode" = T1."CardCode"
WHERE T0."DocStatus" = 'O'
  AND T0."CANCELED" = 'N'
  AND IFNULL(T0."NumAtCard", '') <> ''
  AND DAYS_BETWEEN(T0."DocDate", CURRENT_DATE) > 5
ORDER BY "DiasAbierto" DESC;
SAP Business One Service Layer - real-time monitoring and auditing of integrations
Without SQL auditing, an integration is a black box that is only reviewed when it fails.

Variations and real-world use cases

E-commerce to ERP. The most common case. The store creates the order via Service Layer with the NumAtCard of the shopping cart. In addition, it checks available stock at a certain interval to avoid selling what does not exist.

Customer portal. Read-only: order status, pending invoices, and downloadable documents. For example, a filtered GET request on the "Invoices" endpoint using the authenticated customer's CardCode resolves the 80% error on the portal.

Sales force app. The salesperson takes the order in the field and the app sends it to the ERP. However, it is advisable here to design a local queue: if there is no signal, the order is saved and retried with idempotency control.

Integration with logistics. The logistics operator confirms shipments and the integration creates the delivery associated with the order using the base DocEntry. In this way, document traceability remains intact.

Automation with AI agents. More and more teams are exposing the Service Layer behind an intermediate layer so that conversational assistants can query ERP data. However, that intermediate layer is mandatory: never expose the Service Layer directly to the internet.

Best practices and common mistakes

Use batch transactions for multiple operations. The Service Layer supports $batch with ChangeSets. Therefore, if you need to create an invoice and its payment in a single atomic transaction, group them together: either both are processed or neither is.

Implement idempotency by design. Before creating a document, check if one already exists with that NumAtCard. It is an additional call that saves you the manual cleanup of duplicates, a tedious and accounting-sensitive job.

Never use the manager user. Create a dedicated user with minimal permissions. As a result, your audit queries will be able to accurately distinguish what the machine did and what a person did.

Log every call and every error. The Service Layer returns descriptive error messages in the response body. Save them with their timestamp and payload. Without that log, diagnosing a problem from three weeks ago is impossible.

Respect the license limit. Each active session consumes a connection. Therefore, reuse the session and always close it with Logout.

Do not confuse DocEntry with DocNum. The Service Layer works with DocEntry as the primary key, while the user sees the DocNum. Confusing them is the most common rookie mistake and leads to updates on the wrong documents.

Always test on a copy of the production database. A malformed POST in production cannot be undone with a Ctrl+Z. Furthermore, many documents in SAP Business One do not allow deletion once they have generated journal entries.

Official SAP Resources

Conclusion: integration is a governance decision, not a programming decision

To master SAP Business One Service Layer shift a technical conversation to a strategic one. When your ERP can converse with the rest of the ecosystem in a secure, validated, and auditable way, you stop depending on bridge spreadsheets, manual uploads, and people who «know how it's done.» That is what separates a company that digitizes processes from one that just bought software.

However, the real differentiator is not in the REST call: it is in the audit queries. Any developer can make a POST request. Very few teams know, at nine o'clock on a Monday morning, how many documents the integration took in over the weekend, how many were duplicated, and how many are stuck. That knowledge is what turns an integration into a reliable asset.

If this guide was helpful to you, in the Strategic Circle I publish tutorials like this every week: with production-ready code in SQL Server and SAP HANA, and with the business rationale behind every technical decision. Implement these three queries today, schedule them as a weekly alert, and tell me what you found. There is almost always a surprise waiting in the first result.

Most Read

QlikSense Hierarchy: parent-child chart of accounts expanded by levels
QlikSense Hierarchy: the Chart of Accounts That Doesn't Add Up
QlikSense Sum TOTAL: share of each family over the total
QlikSense Sum TOTAL: the Percentage That Changes When You Filter
SAP Business One Inventory Revaluation - featured image of the tutorial
SAP Business One Inventory Revaluation: Fix Wrongly Loaded Costs
Empty chamber with wooden benches: the counterweight that required being present to be used
The Veto You Had to Say in Person: Your Decisions With No Counterweight
SAP Business One customizations - featured image of the pre-upgrade audit tutorial
SAP Business One Customizations: Pre-Upgrade Audit
SAP Business One Customer Concentration - featured image of the tutorial
SAP Business One Customer Concentration: Measure Your Risk with SQL

RELATED ARTICLES