Integrating Business Systems with the Search API

Introduction

You may want to list related documents on a customer screen in your CRM, show similar FAQs first on an inquiry entry screen, or make reports generated by your in-house system searchable as well. Requests like these can be met by calling the Fess search API (/api/v2) from the server of your business system.

In this article, we work through the following steps with Fess 15.9.

  • Call the search, label, suggest and popular words APIs with curl and check the shape of the responses

  • Create an access token and use the token’s roles to control which documents are returned

  • Write a function that calls the search API from the server side of a business system

  • Register data that cannot be crawled with PUT /api/admin/documents/bulk

  • Prepare for errors and rate limits

How to embed a search box or search page into an existing website (embedding on the browser side, themes, Fess Site Search) is covered in Adding Search to an Existing Website. If you have not yet started Fess and run a crawl, complete Running and Searching Fess with Docker first.

What We Will Build

[User's browser] --> [Business system server] --(with token)--> [Fess /api/v2]
                            The token lives only here

The browser accesses only the business system, and it is the business system’s server that calls Fess. Keep the access token in the server’s environment variables or similar, and never hand it to the browser. The reasons are explained in “Creating an Access Token”.

API Overview

The search-related APIs provided by Fess 15.9 itself are under /api/v2. The ones used in this article are listed below.

Endpoint Purpose
GET /api/v2/search Full-text search. Results are in response.data
GET /api/v2/labels List of labels the caller can use
GET /api/v2/suggest-words Suggestion candidates for a partially typed word
GET /api/v2/popular-words Popular words
GET /api/v2/health Status of the search engine (for use in monitoring, see Fess Operations: Monitoring, Backup, Troubleshooting)
PUT /api/admin/documents/bulk Bulk registration of documents (Admin API)

Every /api/v2 response is wrapped in {"response": {...}}, and response.status is 0 on success. JSON keys are in snake_case.

Note

Fess 15.9 itself does not provide /api/v1. To keep existing clients that call /api/v1 running, you need the fess-webapp-v1-api plugin (it is not bundled in the Docker image). Use /api/v2 for any new integration.

Trying It with curl First

If anonymous search is allowed (“Login Required” under [System] > [General] is off, which is the default), you can call the API without a token. Search terms containing spaces or non-ASCII characters are URL-encoded and sent with -G --data-urlencode. We use jq to make the output easier to read.

$ curl -s -G "http://localhost:8080/api/v2/search" \
    --data-urlencode "q=search guide" \
    --data-urlencode "num=3" \
  | jq '.response | {status, record_count, page_size, data: [.data[] | {doc_id, title, url_link, content_description}]}'

The response looks like this (only the first item of data is shown; the values depend on your environment).

{
  "status": 0,
  "record_count": 12,
  "page_size": 3,
  "data": [
    {
      "doc_id": "5d4c0e0e5a7b4b5c9d2f6a1b3c8e7f90",
      "title": "Search Guide",
      "url_link": "https://fess.codelibs.org/stable/user/index.html",
      "content_description": "The Fess <strong>search</strong> <strong>guide</strong>. ..."
    }
  ]
}

response also contains page_count, next_page, exec_time, query_id and more. Each element of data contains only the fields permitted for API responses, such as title, url, url_link, content_description, last_modified, filetype and score. The full body (content) and the labels (label) are not returned by default. To return more fields, add them to query.additional.api.response.fields in fess_config.properties. content_description is an excerpt in which the search terms are wrapped in <strong> tags, so treat it as HTML or strip the tags when you display it.

Commonly used parameters are listed below.

Parameter Meaning
q Search terms. You can use the same syntax as on the search page (AND, OR, exclusion, field queries and so on)
num / start Number of results per page (default 10; values above the upper limit are reduced to the limit) and the start position (0-based)
sort Sort order. Example: last_modified.desc (most recently updated first)
fields.label Filters by label value. Can be specified more than once

For other parameters (facets, language, geo search and so on), see Search API.

Labels, suggestions and popular words can be called in the same way.

$ curl -s "http://localhost:8080/api/v2/labels" | jq .response
$ curl -s -G "http://localhost:8080/api/v2/suggest-words" --data-urlencode "q=fe" | jq .response
$ curl -s "http://localhost:8080/api/v2/popular-words" | jq .response

The results are in response.labels[] (label and value), response.suggest_words[] (text and types) and response.popular_words (an array of strings), respectively. Why suggestions and popular words may come back empty is explained in “Using Labels, Suggestions and Popular Words”.

Creating an Access Token

Calls from a business system use an access token. A token is given “permissions”, and search results are filtered by those permissions.

Steps

  1. In the admin console, open [System] > [Access Token] and click [Create New].

  2. In “Name”, enter a name that shows what the token is for (for example, crm-search).

  3. In “Permissions”, list the roles of the documents this token may show, one per line. The formats are {role}rolename, {group}groupname and {user}username.

  4. Enter “Expires” in the form 2027-03-31T23:59:59. If left blank, the token does not expire.

  5. Leave “Parameter Name” blank.

  6. Click [Create]. Back on the list, click the name, and note down the value shown in “Token” on the details screen (60 alphanumeric characters).

If you set “Parameter Name”, callers can add permissions through that request parameter. Do not use it unless you have full control over the callers.

Sending the Token

Send the token in the Authorization header. Authorization: <token> without Bearer is also accepted.

$ export FESS_SEARCH_TOKEN=<the token you noted down>
$ curl -s -G "http://localhost:8080/api/v2/search" \
    -H "Authorization: Bearer $FESS_SEARCH_TOKEN" \
    --data-urlencode "q=proposal" | jq '.response.record_count'

Passing the token as a query parameter is disabled, because api.access.token.request.parameter is empty by default. URLs are recorded in access logs, so use the header.

The Token’s Roles Determine the Results

For a request with a token, only the token’s permissions are used as roles. The guest role ({role}guest) that anonymous calls without a token receive is not added, unless the token’s permissions are empty.

On the other hand, when you create a new crawl configuration its permissions field contains {role}guest, so ordinary public documents carry {role}guest. As a result, a token whose only permission is {group}sales makes public documents disappear from the search results. To return both public documents and documents for the sales department, give the token these two lines of permissions:

{role}guest
{group}sales

Once configured, compare record_count for the same search terms without a token and with the token, and confirm that it rises or falls as you expect. Designing permissions on the document side is covered in Controlling Search Results with Roles and Groups.

Why the Token Must Not Reach the Browser

  • Anyone can read a token written in the browser’s JavaScript with the developer tools. Whoever reads it can search every document visible with the token’s permissions, without going through the business system.

  • A token does not belong to an individual user; it bundles the permissions specified when it was issued. If you hand it out to browsers, the differences in permissions between users disappear.

  • Even with “Login Required” turned on, /search, /documents/all, /documents/export, /suggest-words, /labels and /popular-words respond without login as long as a valid token is presented. A leaked token can be used in place of a login.

If you want to vary what is visible depending on the business system’s user, create a separate token for each scope and choose among them on the server side according to the user.

Calling the Search API from the Server

Here is an example Python function to place in the backend of a business system. It uses only the standard library and returns the search results trimmed down to the items the screen needs.

import json
import os
import urllib.error
import urllib.parse
import urllib.request

FESS_URL = os.environ.get("FESS_URL", "http://localhost:8080")
FESS_SEARCH_TOKEN = os.environ["FESS_SEARCH_TOKEN"]


class FessApiError(Exception):
    def __init__(self, http_status, code, retry_after=None):
        super().__init__(f"Fess API error: {http_status} {code}")
        self.http_status = http_status
        self.code = code
        self.retry_after = retry_after


def search_documents(query, label=None, num=5):
    params = [("q", query), ("num", str(num))]
    if label:
        params.append(("fields.label", label))
    url = FESS_URL + "/api/v2/search?" + urllib.parse.urlencode(params)
    req = urllib.request.Request(url, headers={"Authorization": "Bearer " + FESS_SEARCH_TOKEN})
    try:
        with urllib.request.urlopen(req, timeout=15) as res:
            body = json.load(res)
    except urllib.error.HTTPError as e:
        try:
            code = json.load(e)["response"]["error"]["code"]
        except (ValueError, KeyError, TypeError):
            code = "unknown"
        raise FessApiError(e.code, code, e.headers.get("Retry-After")) from e
    response = body["response"]
    return {
        "total": response["record_count"],
        "items": [
            {
                "title": doc.get("title"),
                "url": doc.get("url_link"),
                "snippet": doc.get("content_description"),
                "last_modified": doc.get("last_modified"),
            }
            for doc in response["data"]
        ],
    }

On a CRM customer screen, pass the customer name and a label, as in search_documents("Example Corp.", label="sales_docs"), and render the return value on the screen as is.

  • The timeout is set a little longer than the search timeout on the Fess side (query.timeout, 10000 milliseconds by default).

  • Look at code and retry_after of FessApiError to decide on the message shown to the user and on retries (see “Handling Errors”).

  • content_description contains <strong> tags, so if your template outputs it as HTML, allow only the <strong> tag.

Registering Data from External Systems

Data that cannot be crawled (reports generated by a business system, ticket summaries and so on) can be registered directly in the index with PUT /api/admin/documents/bulk of the Admin API.

Using a Separate Token for the Admin API

The Admin API requires a token whose permissions include {role}admin-api (api.admin.access.permissions=Radmin-api). This permission allows every Admin API endpoint. There is no permission limited to registering documents. Such a token can also manipulate crawl configurations, users and access tokens themselves, so store it as carefully as the administrator’s password.

Also, if you search with a token that has only {role}admin-api, its only role is admin-api, so almost no documents are returned. Use separate tokens for searching and for registering. Under [System] > [Access Token], create one more token whose permissions consist of the single line {role}admin-api (for example, named crm-indexer), and note down its value.

$ export FESS_ADMIN_TOKEN=<the Admin API token you noted down>

Registering Documents

url and title are required. content is the body text, and label is an array of label values.

$ curl -s -X PUT "http://localhost:8080/api/admin/documents/bulk" \
    -H "Authorization: Bearer $FESS_ADMIN_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "documents": [
        {
          "url": "https://crm.example.com/reports/2026-11",
          "title": "Monthly Sales Report November 2026",
          "content": "New business opportunities in November increased over the previous month.",
          "label": ["sales_docs"]
        }
      ]
    }' | jq .response

On success, the result for each document is returned in items. A new document gives CREATED, and an update of an existing document gives OK.

{
  "version": "15.9",
  "status": 0,
  "items": [
    { "result": "CREATED", "id": "9c1e47b2...e04b" }
  ]
}

id is a hash value computed from url and other values (128 hexadecimal digits); the middle is omitted in the example above. Registration is complete when a search for q=monthly sales report with the search token finds the document.

Points to Note When Registering

  • If you omit role, the guest role is assigned and anyone can find the document. To limit who can see it, put values in the internal format into role as an array. In the internal format, {role}x becomes Rx, {group}x becomes 2x and {user}x becomes 1x (for example, "role": ["2sales"]).

  • The document ID is built from url and role (and the virtual host). Sending the same url again updates the document, but sending it with a different role adds it as a separate document and leaves the old one in place.

  • items[].id in the response is the ID in the index, which differs from the document’s doc_id. To delete documents one at a time with DELETE /api/admin/searchlist/doc/{id}, pass the doc_id from the search results. To delete in bulk by a condition, use DELETE /api/admin/searchlist/query (SearchList API).

  • If only some of the documents fail, status becomes 9 and the failed elements contain message. If the request itself is invalid, such as a missing url or title or a value of the wrong type, status becomes 1 and nothing is registered.

Handling Errors

On error, /api/v2 returns an HTTP status and response.error.code.

{"response": {"status": 1, "error": {"code": "invalid_request", "message": "..."}}}

The integrating side should decide in advance how to handle the following.

HTTP error.code Cause and action
400 invalid_request num is 0 or less, the search terms have a syntax error, q exceeds api.param.max.length (1000 characters by default), and so on. Do not retry; review the input
401 auth_required An unregistered or expired token, or no token while “Login Required” is on. An invalid token does not fall back to anonymous access; it results in 401. Recreate the token
503 service_unavailable The search engine could not keep up and rejected the search. Retry-After: 5 is included, so you can retry after waiting 5 seconds
500 internal_error An internal Fess error. Check fess.log under [System Info] > [Log File]

For rate limits, the login, password change, chat and export endpoints each have their own limit; when it is exceeded, 429 rate_limited and Retry-After are returned. The server-wide request limit (rate.limit.enabled) is disabled by default. If you enable it, the body of the 429 returned when the limit is exceeded is {"error":"rate_limit_exceeded", ...}, not the response shape shown above. When calling from a business system’s server, keep in mind that all searches arrive from the same IP address. For details, see Rate Limiting Configuration.

The Admin API (/api/admin/*) uses a different error shape. If there is no token, or the token does not have {role}admin-api, the result is HTTP 401 with response.status set to 3, and the reason is in response.message.

Calling Directly from the Browser (CORS)

CORS does not matter for server-to-server calls. Only when JavaScript in the browser calls Fess on a different origin directly do api.cors.allow.origin (default *), api.cors.allow.methods, api.cors.allow.headers (includes Authorization by default), api.cors.allow.credentials (default true) and api.cors.max.age (default 3600 seconds) in fess_config.properties take effect.

When api.cors.allow.origin is *, requests with credentials such as cookies are not allowed. To let the browser search with the permissions of a logged-in user, list the origins, such as https://portal.example.com (comma-separated). With Docker, you can also specify -Dfess.config.api.cors.allow.origin=https://portal.example.com in FESS_JAVA_OPTS. Restart Fess after making the change. For how to embed on the browser side, see Adding Search to an Existing Website.

References