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

Count results

Get the number of objects a query matches without fetching them, with a count call or with a COUNT aggregate.

For a page that shows "1,204 walls" before it loads them, for paging, or for a check that only needs a number. Counting runs the same query as Run a BQL query but transfers one integer instead of every record.

Before you start#

1. Ask for the count#

The JavaScript and Java SDKs have a dedicated call, queryCount; it takes the query and the models like query and returns the count. Over HTTP, Query counts with "format": "count" and answers {"count": …}.

const walls = await client.bim.queryCount(["<version uuid of the first demo model>"], "GET qid WHERE type = IFCWALL");
console.log(walls);   // a number
long walls = client.bim.queryCount("GET qid WHERE type = IFCWALL", Set.of(UUID.fromString("<version uuid of the first demo model>")));
POST/openapi/ifc/QueryQuery reference
Authorization
Bearer <auth token>
Content-Type
application/json
Body
1 2 3 4 5
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 WHERE type = IFCWALL",
  "format": "count"
}'
Send to see the response

queryCount is on Bim and BimApi. It and the count format accept the same parameters as query (Use query parameters) and count the objects a GET query would return; for a GROUP BY query they count the groups.

2. Or count in the query#

Where no count call is available (the .NET SDK, the PHP client), ask BQL for the count: COUNT(qid) without a GROUP BY yields one record, with the count under the key COUNT as {"name": "COUNT", "value": 13, "unit": "UNITLESS", "type": "int"}. This is a normal query, so it works everywhere Run a BQL query works.

JsonElement result = client.Bim.Query(Guid.Parse("<version uuid of the first demo model>"), "GET COUNT(qid) WHERE type = IFCWALL");
int walls = result[0].GetProperty("COUNT").GetProperty("value").GetInt32();
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 COUNT(qid) 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 COUNT(qid) 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 COUNT(qid) 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 COUNT(qid) 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 COUNT(qid) 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))
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 COUNT(qid) WHERE type = IFCWALL"
}'
Send to see the response

Combined with GROUP BY the same aggregate gives a count per group, GET type, COUNT(qid) GROUP BY type being the classic inventory of a model. AS names the column, GET COUNT(qid) AS walls: the count stays under COUNT in the record, and the answer's columns say that walls is there.

Check#

queryCount of GET qid WHERE type = IFCWALL, the COUNT(qid) record of the same condition, and the length of the array query returns for it are the same number.