How-to guide·QueryJavaScript · Java · .NET · PHP

Run a BQL query

Send a BQL query to one or more versions in JavaScript, Java, .NET, PHP or over HTTP, and read the records that come back.

For every integration that reads model data. A query is a string in BQL (BQL), the models are version UUIDs, and the answer is a list of records whose fields are the features you asked for.

Before you start#

  • A login with the query:run scope and read rights on the versions (Log in with an API token).
  • The version UUIDs (List the tree); the demo models of your instance are the placeholders below.
  • A query. GET qid, type, attribute.Name WHERE type = IFCWALL is a good first one; the cheat sheet is BQL.

1. Run the query#

Classic SDK
const objects = await client.bim.query(["<version uuid of the first demo model>"],
	"GET qid, type, attribute.Name WHERE type = IFCWALL");
for (const object of objects) {
	console.log(object.qid.toString(), object.type, object.attribute.Name);
}
import java.util.UUID;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;

ArrayNode objects = client.bim.query("GET qid, type, attribute.Name WHERE type = IFCWALL",
		UUID.fromString("<version uuid of the first demo model>"));
for (JsonNode object : objects) {
	System.out.println(object.get("qid").asText() + " " + object.get("type").asText() + " " + object.path("attribute").path("Name").asText());
}
using System.Text.Json;

JsonElement objects = client.Bim.Query(Guid.Parse("<version uuid of the first demo model>"),
    "GET qid, type, attribute.Name WHERE type = IFCWALL");
foreach (JsonElement obj in objects.EnumerateArray())
{
    Console.WriteLine($"{obj.GetProperty("qid")} {obj.GetProperty("type")} {obj.GetProperty("attribute").GetProperty("Name")}");
}
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": [
                    {
                      "type": "VersionModelIdentifier",
                      "uuid": "<version uuid of the first demo model>"
                    }
                  ],
                  "query": "GET qid, type, 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": [
        {
          "type": "VersionModelIdentifier",
          "uuid": "<version uuid of the first demo model>"
        }
      ],
      "query": "GET qid, type, 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": [
    {
      "type": "VersionModelIdentifier",
      "uuid": "<version uuid of the first demo model>"
    }
  ],
  "query": "GET qid, type, 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": [
    {
      "type": "VersionModelIdentifier",
      "uuid": "<version uuid of the first demo model>"
    }
  ],
  "query": "GET qid, type, 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": [
    {
      "type": "VersionModelIdentifier",
      "uuid": "<version uuid of the first demo model>"
    }
  ],
  "query": "GET qid, type, 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))

The methods: query(models, query) on Bim.query, BimApi.query(query, versionUuids…) on BimApi.query, Bim.Query(versionUuid, query) on Bim.Query and Bim.Query2(versionUuids, query) on Bim.Query2, IFCApi::query in PHP SDK. All of them call the same server task; the SDKs time out after one minute (Java) or when the transport does. Over HTTP the operation is Query:

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": [{"type": "VersionModelIdentifier", "uuid": BIM_WORKS_FIRST_MODEL}],
  "query": "GET qid, type, attribute.Name WHERE type = IFCWALL"
}'
Send to see the response

With "format": "ifc" or "ifcxml" in the body the same operation answers with the matching objects as an IFC or ifcXML file instead of JSON; count, qids, csv and xlsx give the number of objects, the selection and a table (Output).

2. Read the records#

One record per matching object, with one field per GET column:

JSON#
{
  "qid": "797e993c-a87f-4aa7-9587-c59d30ec5c4e-1316",
  "type": "IFCWALL",
  "attribute": {"Name": "Basic Wall:Interior - 165 Partition:339437"}
}
  • Dotted features become nested objects (attribute.Name is record.attribute.Name); AS aliases become top-level fields; an aggregate keeps its expression as the field name (COUNT(qid)).
  • qid identifies the object: the version's vid, a dash and the object id, see Qid. It is present when you GET qid; a GROUP BY query has no qid unless you COLLECT(qid). Java, .NET, PHP and HTTP give it as that string; the JavaScript SDK gives a Qid object with vid, oid and toString(), and its queryQids variant returns a QidSet for the viewers.
  • type is the IFC entity name in upper case when you asked for it.
  • A feature an object lacks is absent from its record; = null in the WHERE clause finds those objects.
  • The JavaScript SDK unpacks the server's compact wire format (compression: 1, in which version ids and types are sent once and referenced by index) before it returns; over HTTP you get plain records unless you ask for compression: 1 yourself.

3. Cache what you repeat#

The JavaScript query takes a third argument, useCache: with true, the client keeps the result in memory keyed by models, query and parameters, and answers the same call again without a round trip. The cache lives as long as the client and is never invalidated by uploads, so use it for a page that re-asks the same question, not for a long-running application. The server caches too, per model and query text, which is why an identical query is fast the second time in every SDK.

4. Read the errors#

A query the server cannot parse fails with SYNTAX_ERROR; an unknown entity type with UNKNOWN_TYPE; a version you may not read with AuthorizationError.NO_READ_RIGHTS and one that does not exist with MODEL_NOT_FOUND; a missing scope with NON_AUTHORIZED_SCOPE. In JavaScript the promise rejects with the error object (domain, type, code), Java throws BimWorksException with getErrorCode(), .NET throws BimWorksException, PHP an ApiException, and HTTP answers 400, 403 or 404 with the ErrorResponse body. All codes are on Error codes.

Check#

GET type, COUNT(qid) GROUP BY type on the first demo model returns one record per entity type with its count, and the sum of the counts equals queryCount of GET qid (Count results).