How-to guide·QueryJavaScript · Java · PHP

Validate a query

Check that a query parses and uses only available features before running it, from the SDKs or with an empty model set over HTTP, and read the line and column of what fails and the warnings, with suggestions, of a query that parses.

For a query editor, a saved-query feature or a test suite: find out whether a query is acceptable without touching a model. Validation parses the query, applies the same augmentation the real run applies, and checks the features it uses against the instance (for example that the headroom feature is enabled); it does not check whether the models contain anything. A query that does not parse fails and says on which line and column, up to three problems at once; a query that parses comes back with the validator's warnings about it, such as an IFC class in the wrong case, each with what was probably meant.

Live demo#

Validate a query and read the messageLive demo
No model is loaded; the query is validated by the server. Open BIM.works and sign in once in this browser.

The buttons load sample queries, valid and broken; Validate (or Ctrl+Enter in the editor) sends the text to the server and shows the message that comes back.

Before you start#

1. Validate#

Classic SDK
try {
	const {messages} = await client.bim.validateQuery("GET qid, attribute.Name WHERE type = IFCWALL");
	console.log(messages.length === 0 ? "valid" : messages);
} catch (e) {
	const error = e.error || e.response?.error || e;
	console.log(error.domain, error.type);   // BimWorksQueryError SYNTAX_ERROR
}
boolean valid = client.bim.validate("GET qid, attribute.Name WHERE type = IFCWALL");
// The same check, with the validator's warnings about a query that parses
List<BimApi.QueryValidationMessage> messages = client.bim.validateQuery("GET qid, attribute.Name WHERE type = IFCWALL");
OpenAPI SDK
import nl.bimbase.bimworks.sdk.api.AuthApi;
import nl.bimbase.bimworks.sdk.api.IfcApi;
import nl.bimbase.bimworks.sdk.client.ApiClient;
import nl.bimbase.bimworks.sdk.model.Auth;
import nl.bimbase.bimworks.sdk.model.LoginWithApiTokenRequest;
import nl.bimbase.bimworks.sdk.model.QueryRequest;

public class Example {
    public static void main(String[] args) throws Exception {
        // 1. Connect to BIM.works and log in with your API token
        ApiClient client = new ApiClient();
        client.updateBaseUri("https://bim.works/openapi");
        Auth auth = new AuthApi(client)
                .loginWithApiToken(new LoginWithApiTokenRequest().token("<your API token>"))
                .getAuth();
        client.setRequestInterceptor(builder -> builder.setHeader("Authorization", "Bearer " + auth.getBase64()));

        // 2. The request
        QueryRequest request = client.getObjectMapper().readValue("""
                {
                  "models": [],
                  "query": "GET qid, attribute.Name WHERE type = IFCWALL"
                }
                """, QueryRequest.class);

        // 3. The call
        var result = new IfcApi(client).query(request);

        // 4. The result
        System.out.println(client.getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(result));
    }
}
using System.Text.Json;
using BIMworks.Sdk.Api;
using BIMworks.Sdk.Client;
using BIMworks.Sdk.Extensions;
using BIMworks.Sdk.Model;
using Microsoft.Extensions.DependencyInjection;

// 1. Connect to BIM.works and log in with your API token
IServiceProvider Connect(string bearer)
{
    var services = new ServiceCollection();
    services.AddApi(options =>
    {
        options.AddTokens(new BearerToken(bearer));
        options.AddApiHttpClients(http =>
        {
            http.BaseAddress = new Uri("https://bim.works" + "/openapi");
            http.Timeout = Timeout.InfiniteTimeSpan;
        });
    });
    return services.BuildServiceProvider();
}
var login = await Connect("").GetRequiredService<IAuthApi>().LoginWithApiTokenAsync(new LoginWithApiTokenRequest("<your API token>"));
var auth = login.Ok()?.Auth ?? throw new HttpRequestException(login.RawContent, null, login.StatusCode);
var client = Connect(auth.Base64);
var json = client.GetRequiredService<JsonSerializerOptionsProvider>().Options;

// 2. The request
var request = JsonSerializer.Deserialize<QueryRequest>("""
    {
      "models": [],
      "query": "GET qid, attribute.Name WHERE type = IFCWALL"
    }
    """, json);

// 3. The call
var response = await client.GetRequiredService<IIFCApi>().QueryAsync(request);

// 4. The result
var result = response.Ok() ?? throw new HttpRequestException(response.RawContent, null, response.StatusCode);
Console.WriteLine(JsonSerializer.Serialize(result, json));
import { AuthApi, Configuration, IFCApi, QueryRequestFromJSON } from "@bimworks/sdk";

// 1. Connect to BIM.works and log in with your API token
const basePath = "https://bim.works/openapi";
const auth = await new AuthApi(new Configuration({ basePath }))
  .loginWithApiToken({ loginWithApiTokenRequest: { token: "<your API token>" } });
const client = new Configuration({ basePath, accessToken: typeof auth === "string" ? auth : auth.base64 });

// 2. The request
const request = QueryRequestFromJSON({
  "models": [],
  "query": "GET qid, attribute.Name WHERE type = IFCWALL"
});

// 3. The call
const result = await new IFCApi(client).query({ queryRequest: request });

// 4. The result
console.log(JSON.stringify(result, null, 2));
<?php
require __DIR__ . '/vendor/autoload.php';

use BIMworks\Api\AuthApi;
use BIMworks\Api\IFCApi;
use BIMworks\Configuration;
use BIMworks\Model\LoginWithApiTokenRequest;
use BIMworks\Model\QueryRequest;
use BIMworks\ObjectSerializer;

// 1. Connect to BIM.works and log in with your API token
$client = (new Configuration())->setHost('https://bim.works/openapi');
$auth = (new AuthApi(config: $client))->loginWithApiToken(new LoginWithApiTokenRequest(['token' => "<your API token>"]));
$client->setAccessToken($auth->getBase64());

// 2. The request
$request = ObjectSerializer::deserialize(<<<'JSON'
{
  "models": [],
  "query": "GET qid, attribute.Name WHERE type = IFCWALL"
}
JSON, QueryRequest::class);

// 3. The call
$result = (new IFCApi(config: $client))->query($request);

// 4. The result
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), PHP_EOL;
import json

import bimworks

# 1. Connect to BIM.works and log in with your API token
client = bimworks.ApiClient(bimworks.Configuration(host="https://bim.works/openapi"))
auth = bimworks.AuthApi(client).login_with_api_token(
    bimworks.LoginWithApiTokenRequest(token="<your API token>"))
client.configuration.access_token = auth.actual_instance.var_base64

# 2. The request
request = bimworks.QueryRequest.from_json(r"""
{
  "models": [],
  "query": "GET qid, attribute.Name WHERE type = IFCWALL"
}
""")

# 3. The call
result = bimworks.IFCApi(client).query(request)

# 4. The result
print(json.dumps(client.sanitize_for_serialization(result), indent=2))

validateQuery on Bim rejects with the error for a query that does not parse and otherwise resolves with {messages}, the validator's warnings (step 2), empty for a clean query. BimApi.validate on BimApi returns false for a query the server rejects and throws BimWorksException for any other failure (no rights, no connection); BimApi.validateQuery returns the messages and throws BimWorksException for a query that does not parse. All of them call the ValidateQuery task. The .NET SDK has no validation call; use the HTTP route.

Over HTTP, Query with an empty models array validates: a 200 with an empty result means the query parses and its features are available, a 400 with SYNTAX_ERROR means it does not parse. This route has no room for the validator's warnings: WHERE type = IfcWall gets the same empty 200 here and fails with UNKNOWN_TYPE once it runs on a model.

POST/openapi/ifc/QueryQuery reference
Authorization
Bearer <auth token>
Content-Type
application/json
Body
1 2 3 4
Authorization: Bearer <auth token>
Content-Type: application/json
Accept: application/json
curl -X POST "$BIMWORKS_URL/openapi/ifc/Query" \
  -H "Authorization: Bearer $BIMWORKS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
  "models": [],
  "query": "GET qid, attribute.Name WHERE type = IFCWALL"
}'
Send to see the response

2. Read the errors#

The message is the same everywhere: in the API error, in the editor markers of the app, in the SDKs, and in the assistant that repairs actions in the chat. Show it to the user as it is; in JavaScript it is the userSafeMessage of the error:

JavaScript#
try {
	await client.bim.validateQuery("GET attribute.Name\nWHER type = IFCWALL");
} catch (e) {
	const error = e.error || e.response?.error || e;
	console.log(error.userSafeMessage || error.message);   // line 2:1: ...
}

A query that parses can still be wrong. What the validator finds in it comes back in messages, each with a severity (ERROR or WARNING, as the editor marks it), the code of the check that found it, the line and column, and the same message the editor shows:

JavaScript#
const {messages} = await client.bim.validateQuery("GET attribute.Name\nWHERE type = IfcWall");
for (const message of messages) {
	console.log(message.severity, message.code, message.message);
	// WARNING unknownIfcClass line 2:14: IfcWall is not a known IFC class (IFC class names are uppercase); did you mean IFCWALL?
}
  • Positions. A syntax error reads line 3:14: mismatched input '…', and a query with several errors lists up to three of them, separated by ;. A text that is not BQL at all fails at its first token: line 1:1: no viable alternative at input 'THIS'. Every parse error is reported; none produces a broken query that fails later.
  • Suggestions. The validation knows the schema: an IFC class in the wrong case in WHERE type = IfcWall gets is not a known IFC class (IFC class names are uppercase); did you mean IFCWALL?, an attribute in the wrong case is told that attribute names are case-sensitive, with the right spelling. About thirty semantic checks — regular-expression validity, BETWEEN bounds, FIRST without GROUP BY, unit pitfalls — come back as the messages of the ValidateQuery task (the SDK calls above), as markers in the web editor, and to the assistant in the chat. The query still validates, so a client that only tests for success keeps working; the Query route with an empty model set does not return them. The other languages' checks, such as the closest existing name for a misspelt block or configuration key in a BRL report, show in their editors and in the chat.
  • Refusals. A feature that a workspace visibility rule hides from you comes back the same way, as an ERROR message with the code FEATURE_NOT_VISIBLE: the query parses, but Query2 refuses to run it.
  • Every language. BQL, BVL, BUL, BCL, BRL, BSL, BCOL and BFL report their errors the same way (explanation/the-query-languages#errors-that-say-where). In the app, the action editors mark the line in the gutter and show the message, and the Validate button of a query does the same without running it. Running an invalid query with Query2 reports the same message instead of running.

The codes:

  • SYNTAX_ERROR: the text does not parse; the message names the position and what was expected.
  • FEATURE_DISABLED: a feature the instance has switched off.
  • FEATURE_NOT_VISIBLE: the code of the ERROR message for a feature a visibility rule hides; the query validates, running it is refused.
  • UNKNOWN_TYPE: an IFC class that is not in the IFC schemas, raised when the query runs; validation warns about it beforehand with the unknownIfcClass message.
  • MISSING_QUERY: a run (Query2, QueryCount) without a query.

The complete list is on Error codes under BimWorksQueryError and BimWorksErrorCode.

Check#

GET qid WHERE type = IFCWALL validates with no messages; GET qid WHERE type = IfcWall validates with one WARNING, unknownIfcClass, that suggests IFCWALL; GET qid WHERE type = IFCWALL AND (a dangling AND) fails with SYNTAX_ERROR; running the valid query afterwards (Run a BQL query) returns objects.