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/bulkPrepare 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
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.
The response looks like this (only the first item of data is shown; the values depend on your environment).
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.
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
In the admin console, open [System] > [Access Token] and click [Create New].
In “Name”, enter a name that shows what the token is for (for example,
crm-search).In “Permissions”, list the roles of the documents this token may show, one per line. The formats are
{role}rolename,{group}groupnameand{user}username.Enter “Expires” in the form
2027-03-31T23:59:59. If left blank, the token does not expire.Leave “Parameter Name” blank.
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.
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:
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,/labelsand/popular-wordsrespond 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.
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
codeandretry_afterofFessApiErrorto decide on the message shown to the user and on retries (see “Handling Errors”).content_descriptioncontains<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.
Registering Documents
url and title are required. content is the body text, and label is an array of label values.
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.
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 intoroleas an array. In the internal format,{role}xbecomesRx,{group}xbecomes2xand{user}xbecomes1x(for example,"role": ["2sales"]).The document ID is built from
urlandrole(and the virtual host). Sending the sameurlagain updates the document, but sending it with a differentroleadds it as a separate document and leaves the old one in place.items[].idin the response is the ID in the index, which differs from the document’sdoc_id. To delete documents one at a time withDELETE /api/admin/searchlist/doc/{id}, pass thedoc_idfrom the search results. To delete in bulk by a condition, useDELETE /api/admin/searchlist/query(SearchList API).If only some of the documents fail,
statusbecomes 9 and the failed elements containmessage. If the request itself is invalid, such as a missingurlortitleor a value of the wrong type,statusbecomes 1 and nothing is registered.
Using Labels, Suggestions and Popular Words
Creating Categories with Labels
The labels used for filtering with fields.label are created under [Crawler] > [Label]. “Value” can contain only alphanumeric characters and underscores (sales-docs and non-ASCII characters cannot be used). A crawled document gets a label when its URL matches the label’s “Included Paths” (Searching Websites and File Servers Together). For documents registered in bulk, send label as in the previous section.
/api/v2/labels returns only the labels that the caller’s roles can use. Labels also have permissions, so labels that do not match the token’s permissions do not appear in the list. Build the category list of a portal from label (display name) and value (the value to pass to fields.label) in this response.
Suggestions
/api/v2/suggest-words returns candidates that match q as a prefix. The number of candidates is set with num (default 10), and the target fields are specified by repeating fn. Candidates come from words in crawled documents (“Suggest from Documents” under [System] > [general]), from search terms (“Suggest from Search Terms” on the same screen), and from suggest words registered by an administrator. Words from documents do not appear as candidates until the “Suggest Indexer” job in the scheduler (once a day by default) has run. Candidates are also filtered by the caller’s roles.
Popular Words
/api/v2/popular-words returns the most frequently searched terms among those collected from the search log. If an empty array is returned, check the following points.
If “Popular Word Response” under [System] > [general] (
web.api.popularword, on by default) is off, the call fails withinvalid_request(HTTP 400).“Suggest from Search Terms” must be on. Search terms are collected only while this setting is on.
The same term must have been searched 10 times or more (
suggest.popular.word.query.freq=10). Repeated searches from the same session within one minute count as one. Right after installation, an empty result is normal.Only searches made with the guest role alone are counted (
suggest.search.log.permissions={user}guest,{role}guest). Searches by tokens with{group}salesor the like, and by logged-in users, are not counted.Popular words are also filtered by the caller’s roles. The aggregated terms carry only the guest role, so a token whose permissions do not include
{role}guestalways gets an empty result.Results are cached, so they do not change immediately even as searches increase.
Changing seed returns a different combination from the candidates.
Handling Errors
On error, /api/v2 returns an HTTP status and response.error.code.
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.
What to Read Next
To embed a search box or search page into an existing site: Adding Search to an Existing Website
To design which documents each token or user can see: Controlling Search Results with Roles and groups
To use the API for health checks and monitoring: Fess Operations: Monitoring, Backup, Troubleshooting
To manage settings as code with the Admin API and fessctl: Fess Settings as Code for Reproducible Environments
To protect your search platform, including the operation of SSO and access tokens: Protecting Search with SSO and Access Control