Tutorial - Autodesk Revit
Level: Intermediate
Time: 30–45 min for one workflow
Prerequisites:
- A VIKTOR account with App Builder access or the VIKTOR CLI for local development.
- For App Builder, your environment administrator must enable Allow Python-based workers in the app builder.
- Revit 2024 or newer, pyRevit 7.0 or newer, and VIKTOR Desktop on the same Windows computer.
- An open Revit model. Use a writable copy for the workflows that change the model.
Introduction
Build an app that works with the model you have open in Revit. Use the App Builder to color structural elements, measure concrete volumes, estimate wall carbon and cost, place room tags, dimension grids, or review doors. Each prompt creates a separate app. The Local development tab shows how to run the category coloring sample from GitHub.
1. Connect Revit to VIKTOR
The VIKTOR Revit worker sends app requests to pyRevit, which runs them in the model you have open. Follow the steps below to set up both tools on the Windows computer that runs Revit. Revit integration guide
- Install pyRevit and attach it to your Revit version.
- Open Revit and enable the pyRevit Agent Runtime. Set Model Changes to Auto for this tutorial so app actions apply directly to your test model. Select Save Settings and Reload.
- Sign in to VIKTOR Desktop on the Windows computer that runs Revit. Use the same Windows account for both. Add a Revit worker, select its Python executable, and start the worker.
- Run
pyrevit agent statusin a terminal on that computer to check that the Agent Runtime can see Revit. In the VIKTOR app, open Integration status to check that the Revit worker is connected.
Use the Path to the Python executable field to select the Python installation for the worker.

For the App Builder, your environment administrator must enable Allow Python-based workers in the app builder. If the App Builder asks about your setup, confirm that the worker is connected, the model is open, and Model Changes is set to Auto.
2. Open a sample model
Each prompt names the Snowdon Towers model to open. Choose the link for your Revit version from 2024 through 2027. On the Autodesk sample files page, select Architectural or Structural under Snowdon Towers as specified in the prompt. Open the file on the Windows computer that runs the worker and keep the model active in Revit while you use the app. You can also use a model with the same categories and views.
3. Choose your approach
- Prompt guide
- Local development
Select the arrow on a prompt to open it in the App Builder. Check the generated inputs and the model shown in the app before you run an action. The app layout can differ from the examples below.
Prompt 1 – Color structural elements by category
Give columns, framing, and floors different colors in one Revit view. Start here to check that VIKTOR can read the model and apply a visible change.
Open Snowdon Towers Sample Structural. Revit 2024 download · Revit 2025 sample files · Revit 2026 sample files · Revit 2027 sample files
Color structural elements in Revit
Open the Structure Only 3D view in the structural model. In the app, select Load views, choose Active view, and set a color for each category. Select Apply colors and check the element counts.

Check the same view in Revit. The example shows red columns, blue framing, and green floors.

Prompt 2 – Measure concrete volumes by type
Compare concrete quantities for slab and wall types in one dashboard.
Open Snowdon Towers Sample Architectural. Revit 2024 download · Revit 2025 sample files · Revit 2026 sample files · Revit 2027 sample files
Measure Revit concrete volumes by type
Select Load Concrete Volumes to populate the dashboard. For a floor or wall with several materials, compare the reported volume with the concrete material volume in a Revit material takeoff.

Prompt 3 – Estimate wall carbon and cost
Use the modeled area of each basic wall type and the rates you enter to estimate its carbon and cost. Store the rates on the Revit type so you can read them again.
Open Snowdon Towers Sample Architectural. Revit 2024 download · Revit 2025 sample files · Revit 2026 sample files · Revit 2027 sample files
Estimate Revit wall carbon and cost
Select Load / Reload Wall Data to read the wall types, counts, and areas from Revit.

Enter the rates directly in Wall Type Rates. Check that the totals update as you edit. An area of 6 m² at 20 kg CO₂e/m² and 30 USD/m² gives 120 kg CO₂e and 180 USD.
Select Save All Rates to Revit below the table.
After the app confirms the save, select a wall in Revit, open Edit Type, and check the three values under Data. Select Load / Reload Wall Data in the app to read the saved values again.

Prompt 4 – Add missing room tags
A room tag displays information from a room, such as its number or name, on a plan. Use the table to find rooms that still need a tag on the selected plan.
Open Snowdon Towers Sample Architectural. Revit 2024 download · Revit 2025 sample files · Revit 2026 sample files · Revit 2027 sample files
Find and place missing Revit room tags
Select Rooms - L1 - Block 37 in the architectural model. Place the missing tags, then open the plan and check the tags in Revit. Repeat the action and check that it adds zero tags. In the example run, the app showed eight tagged rooms.

In Revit, zoom in on the plan to check the tags against the room outlines. The close-up shows Commercial/Retail 105 and Residential Lobby 106.

Prompt 5 – Dimension grids on a plan
Add dimensions between selected grid pairs and verify their values in Revit.
Open Snowdon Towers Sample Architectural. Revit 2024 download · Revit 2025 sample files · Revit 2026 sample files · Revit 2027 sample files
Add Revit plan grid dimensions
On L2, try grid pairs 1–2, 1–3, and 1–4. Compare the table values with the dimensions in Revit. Repeat the action and check that the table shows the same three IDs.

The L2 close-up shows all three dimension values in the project's units.

Prompt 6 – Review doors
Use the dashboard to find doors that need review and locate them in a 3D Revit view.
Open Snowdon Towers Sample Architectural. Revit 2024 download · Revit 2025 sample files · Revit 2026 sample files · Revit 2027 sample files
Snowdon Door Review
Run the door check and filter the results by level. Click Create 3D Review View in Revit. Open the view and use the door IDs from the table to verify a few of the colored doors.

Create a new VIKTOR app
Build the category coloring app from Prompt 1 in stages. The app counts elements in a Revit view and applies a color to each selected category through the Revit worker.
To start with all files in place, get the complete app on GitHub.
Open Snowdon Towers Sample Structural. Revit 2024 download · Revit 2025 sample files · Revit 2026 sample files · Revit 2027 sample files
Install the VIKTOR CLI and sign in. Run this command to create an editor app.
viktor-cli create-app "Revit colour by category" --init --app-type editor --registered-name revit-colour-by-category
Open the new app folder in your code editor. Create a revit_scripts folder next to app.py.
Configure the app and dependencies
In the pyRevit Agent Runtime settings, use IronPython as the default script engine for this sample.
Add the Revit worker integration in viktor.config.toml. Use the registered name from your create-app command.
app_type = "editor"
registered_name = "revit-colour-by-category"
python_version = "3.12"
worker_integrations = [
"revit",
]
Set the VIKTOR SDK version in requirements.txt.
viktor==14.38.0
1. Count elements in the Revit view
Create revit_scripts/model_info.py. pyRevit supplies doc, DB, and inputs to the script. Use them to find the view, count elements in each requested category, and return the counts in result.
# Runs inside Revit (Agent Runtime, query mode).
# Returns the model, the target view and the number of elements per requested category in that view.
def get_target_view(target):
if target.get("mode") == "named":
for v in DB.FilteredElementCollector(doc).OfClass(DB.View):
if not v.IsTemplate and v.Name == target.get("name"):
return v
raise Exception("No view named '%s' found in the model." % target.get("name"))
view = doc.ActiveView
if view is None or view.ViewType in (DB.ViewType.DrawingSheet, DB.ViewType.Schedule, DB.ViewType.ProjectBrowser):
raise Exception("The active view '%s' cannot show model elements. Open a plan, section or 3D view." % (view.Name if view else "-"))
return view
view = get_target_view(inputs.get("target", {"mode": "active"}))
counts = []
for name in inputs.get("categories", []):
bic = getattr(DB.BuiltInCategory, name)
n = DB.FilteredElementCollector(doc, view.Id).OfCategory(bic).WhereElementIsNotElementType().GetElementCount()
counts.append({"category": name, "label": DB.LabelUtils.GetLabelFor(bic), "count": n})
result = {"model": doc.Title, "view": view.Name, "view_type": str(view.ViewType), "counts": counts}
2. Apply category colors in Revit
Create revit_scripts/colour_by_category.py. For each rule, collect the elements of that category in the view and apply graphic overrides in one Revit transaction. Return the number of elements for each rule.
# Runs inside Revit (Agent Runtime, modify mode).
# Applies a solid colour override to every element of each category in the target view,
# or clears the overrides when inputs["reset"] is true.
def get_target_view(target):
if target.get("mode") == "named":
for v in DB.FilteredElementCollector(doc).OfClass(DB.View):
if not v.IsTemplate and v.Name == target.get("name"):
return v
raise Exception("No view named '%s' found in the model." % target.get("name"))
view = doc.ActiveView
if view is None or view.ViewType in (DB.ViewType.DrawingSheet, DB.ViewType.Schedule, DB.ViewType.ProjectBrowser):
raise Exception("The active view '%s' cannot show model elements. Open a plan, section or 3D view." % (view.Name if view else "-"))
return view
view = get_target_view(inputs.get("target", {"mode": "active"}))
reset = inputs.get("reset", False)
solid = None
for fp in DB.FilteredElementCollector(doc).OfClass(DB.FillPatternElement):
if fp.GetFillPattern().IsSolidFill:
solid = fp
break
summary = []
t = DB.Transaction(doc, "VIKTOR colour by category")
t.Start()
for rule in inputs["rules"]:
bic = getattr(DB.BuiltInCategory, rule["category"])
settings = DB.OverrideGraphicSettings()
if not reset:
r, g, b = rule["color"]
colour = DB.Color(r, g, b)
settings.SetProjectionLineColor(colour)
settings.SetCutLineColor(colour)
if solid is not None:
settings.SetSurfaceForegroundPatternId(solid.Id)
settings.SetSurfaceForegroundPatternColor(colour)
settings.SetCutForegroundPatternId(solid.Id)
settings.SetCutForegroundPatternColor(colour)
ids = DB.FilteredElementCollector(doc, view.Id).OfCategory(bic).WhereElementIsNotElementType().ToElementIds()
for element_id in ids:
view.SetElementOverrides(element_id, settings)
summary.append({"category": rule["category"], "label": DB.LabelUtils.GetLabelFor(bic),
"color": rule.get("color"), "elements": len(ids)})
t.Commit()
result = {"model": doc.Title, "view": view.Name, "reset": reset, "summary": summary}
3. Connect the worker to pyRevit
Create revit_scripts/run_agent.py. The worker receives the selected script as revit_task.py and its settings in job.json. It runs the script in the open Revit model and writes the pyRevit response to output.json.
# Worker script: runs a Revit script in the open Revit model through the pyRevit Agent Runtime.
import json
import os
import shutil
import subprocess
from pathlib import Path
root = Path(__file__).resolve().parent
job = json.loads((root / "job.json").read_text(encoding="utf-8"))
mode = job.get("mode", "query")
if mode not in ("query", "dry_run", "modify"):
raise ValueError("Invalid mode: " + mode)
pyrevit = shutil.which("pyrevit") or os.path.expandvars(r"%APPDATA%\pyRevit-Master\bin\pyrevit.exe")
command = [
pyrevit, "agent", "run", str(root / "revit_task.py"),
"--mode=" + mode,
"--title=" + job.get("title", "VIKTOR"),
"--inputs=" + json.dumps(job.get("inputs", {})),
"--timeout=" + str(job.get("timeout", 240)),
]
if job.get("revit"):
command.append("--revit=" + str(job["revit"])) # Revit year, when several versions are running
process = subprocess.run(command, capture_output=True, text=True, timeout=job.get("timeout", 240) + 30)
try:
response = json.loads(process.stdout[process.stdout.find("{"):])
except ValueError:
response = {"status": "error", "error": (process.stderr or process.stdout).strip()}
(root / "output.json").write_text(json.dumps(response, indent=2), encoding="utf-8")
4. Add the app inputs
Replace the generated app.py with the code below. The inputs select a Revit view and collect one color per category. The run_agent helper sends the selected script and its inputs to the worker with RevitAnalysis.
import json
from io import BytesIO
from pathlib import Path
import viktor as vkt
SCRIPTS = Path(__file__).parent / "revit_scripts"
CATEGORIES = {
"OST_StructuralColumns": "Structural Columns",
"OST_StructuralFraming": "Structural Framing",
"OST_StructuralFoundation": "Structural Foundations",
"OST_Floors": "Floors",
"OST_Walls": "Walls",
"OST_Roofs": "Roofs",
"OST_Columns": "Columns",
"OST_Stairs": "Stairs",
"OST_Railings": "Railings",
"OST_Doors": "Doors",
"OST_Windows": "Windows",
"OST_GenericModel": "Generic Models",
}
CATEGORY_OPTIONS = [vkt.OptionListElement(value, label) for value, label in CATEGORIES.items()]
def run_agent(task_script, mode="query", inputs=None, title="VIKTOR", timeout=240):
"""Send a Revit script to the Revit worker and return the pyRevit Agent Runtime response."""
job = {"mode": mode, "title": title, "inputs": inputs or {}, "timeout": timeout}
analysis = vkt.revit.RevitAnalysis(
script=vkt.File.from_path(SCRIPTS / "run_agent.py"),
files=[
("revit_task.py", vkt.File.from_path(SCRIPTS / task_script)),
("job.json", BytesIO(json.dumps(job).encode())),
],
output_filenames=["output.json"],
)
analysis.execute(timeout=timeout + 60)
response = json.loads(analysis.get_output_file("output.json").getvalue())
if response.get("status") != "ok":
error = response.get("error")
message = error.get("message") if isinstance(error, dict) else error
raise vkt.UserError(f"Revit run failed: {message}")
return response
def target_view(params):
if params.target == "named":
if not params.view_name:
raise vkt.UserError("Enter the name of the Revit view.")
return {"mode": "named", "name": params.view_name}
return {"mode": "active"}
def colour_rules(params):
rules, seen = [], set()
for i, row in enumerate(params.rules, start=1):
if not row.category:
raise vkt.UserError(f"Select a category in rule {i}.")
if row.category in seen:
raise vkt.UserError(f"{CATEGORIES[row.category]} is used in more than one rule.")
if row.color is None:
raise vkt.UserError(f"Select a colour in rule {i}.")
seen.add(row.category)
rules.append({"category": row.category, "color": [row.color.r, row.color.g, row.color.b]})
if not rules:
raise vkt.UserError("Add at least one colour rule.")
return rules
class Parametrization(vkt.Parametrization):
intro = vkt.Text(
"# Revit colour by category\n"
"Colours the elements of each selected category in the Revit model that is open on the worker. "
"The app uses the **pyRevit Agent Runtime**: the table reads the model (`query` mode) and the buttons "
"write the colour overrides to the view (`modify` mode). Every change is one undo entry in Revit."
)
target = vkt.OptionField(
"Revit view",
options=[vkt.OptionListElement("active", "Active view"), vkt.OptionListElement("named", "View by name")],
default="named",
variant="radio-inline",
flex=100,
)
view_name = vkt.TextField(
"View name",
default="Structure Only",
visible=vkt.IsEqual(vkt.Lookup("target"), "named"),
description="Name of a plan, section or 3D view in the Revit model.",
)
rules_text = vkt.Text("## Colour rules\nAdd one rule per category.")
rules = vkt.DynamicArray(
"Colour rules",
row_label="Rule",
default=[
{"category": "OST_StructuralColumns", "color": vkt.Color(230, 57, 70)},
{"category": "OST_StructuralFraming", "color": vkt.Color(29, 53, 87)},
{"category": "OST_Floors", "color": vkt.Color(168, 218, 220)},
],
)
rules.category = vkt.OptionField("Category", options=CATEGORY_OPTIONS, flex=60)
rules.color = vkt.ColorField("Colour", default=vkt.Color(69, 123, 157), flex=40)
preview = vkt.BooleanField(
"Preview only (dry run)",
default=False,
description="Runs the change in Revit and rolls it back, without changing the view.",
)
apply = vkt.ActionButton("Apply colours in Revit", method="apply_colours", longpoll=True, flex=50)
reset = vkt.ActionButton("Reset colours", method="reset_colours", longpoll=True, flex=50)
5. Add the table and action buttons
Append the Controller below to the same app.py. The table calls model_info.py in query mode and displays the model, view, counts, and colors. The action buttons call colour_by_category.py to apply or clear overrides.
class Controller(vkt.Controller):
label = "Revit colour by category"
parametrization = Parametrization
@vkt.TableView("Elements per category", duration_guess=10)
def elements_per_category(self, params, **kwargs):
rules = colour_rules(params)
response = run_agent(
"model_info.py",
mode="query",
inputs={"target": target_view(params), "categories": [r["category"] for r in rules]},
title="VIKTOR model info",
)
result = response["result"]
colours = {r["category"]: vkt.Color(*r["color"]) for r in rules}
rows = [
[c["label"], c["count"], vkt.TableCell("", background_color=colours[c["category"]])]
for c in result["counts"]
]
return vkt.TableResult(
rows,
column_headers=["Category", f"Elements in '{result['view']}'", "Colour"],
row_headers=[result["model"]] * len(rows),
)
def apply_colours(self, params, **kwargs):
response = run_agent(
"colour_by_category.py",
mode="dry_run" if params.preview else "modify",
inputs={"target": target_view(params), "rules": colour_rules(params)},
title="VIKTOR colour by category",
timeout=600, # leave time to approve the change when the pyRevit policy is 'ask'
)
result = response["result"]
total = sum(s["elements"] for s in result["summary"])
action = "Previewed" if params.preview else "Coloured"
vkt.UserMessage.success(
f"{action} {total} elements in view '{result['view']}' ({response.get('decision')})."
)
def reset_colours(self, params, **kwargs):
response = run_agent(
"colour_by_category.py",
mode="modify",
inputs={"target": target_view(params), "rules": colour_rules(params), "reset": True},
title="VIKTOR reset colours",
timeout=600,
)
total = sum(s["elements"] for s in response["result"]["summary"])
vkt.UserMessage.success(f"Reset the colour of {total} elements in view '{response['result']['view']}'.")
6. Run and check the app
From the app folder, install the dependencies and start the app.
viktor-cli clean-start
- In Revit, open CoverSheet in the Snowdon Towers structural model, or open another 3D view with floors, columns, and framing.
- Open the development URL printed by the CLI. Select Active view and review the entries under Colour rules.
- Generate the Elements per category table and check the view name and counts.
- Select Apply colours in Revit. Check the reported count and confirm the colors in Revit.


Use Undo in Revit to restore the previous state. Reset colours clears the graphic overrides for the selected elements, including overrides that were present before the run.
Complete code
Clone the finished sample and follow its README to run the app with all files in place. Revit category coloring sample on GitHub
Conclusion
Adapt one of the prompts to a model you work with. Change the categories, rates, or checks to suit your project, then verify the results in Revit.
For models stored in Autodesk Construction Cloud, try viewing a model, running a quantity takeoff, or checking element properties in the Autodesk Forma / ACC tutorial.