Skip to content

Fix airflowctl create assets command not working - #55702

Closed
sidshas03 wants to merge 18 commits into
apache:mainfrom
sidshas03:main
Closed

sidshas03 wants to merge 18 commits into
apache:mainfrom
sidshas03:main

Conversation

@sidshas03

@sidshas03 sidshas03 commented Sep 16, 2025 •

Copy link
Copy Markdown
Contributor

Problem:

  • airflowctl create assets command was failing because the required API endpoint and client method were missing
  • Users could not create assets via the CLI tool

Root Cause:

  • Missing POST /assets endpoint in Airflow core API
  • Missing create() method in AssetsOperations class
  • Missing CreateAssetBody data model for asset creation requests

Solution:

  1. Added CreateAssetBody data model with proper validation:

    • name (required, 1-1500 chars)
    • uri (required, 1-1500 chars)
    • group (optional, max 1500 chars)
    • extra (optional dict)
  2. Implemented POST /assets API endpoint with:

    • Duplicate asset checking (name + uri uniqueness)
    • Proper error handling (400 for bad requests, 409 for conflicts)
    • Authentication and authorization
    • Action logging for audit trails
  3. Added create() method to AssetsOperations class:

    • Proper HTTP POST request handling
    • JSON serialization with date safety
    • Error handling and response parsing
  4. Updated generated datamodels to include CreateAssetBody

Testing:

  • Verified airflowctl assets create command is now available
  • Confirmed parameter validation works correctly
  • Tested API integration (fails gracefully when no server/credentials)
  • All linting checks pass

The airflowctl create assets command now works as expected and allows users to create assets via the CLI.

@jason810496 jason810496 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! Thanks for the PR!

It would be nice to add the test for API. Thanks!

@sidshas03 sidshas03 left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jason810496 thanks for the review! I’ve added FastAPI tests for POST /assets:
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_assets_post.py
Covers:
• ✅ Happy path (200/201), asserts name & uri
• ✅ Duplicate create (409) with uuid4() to avoid collisions
• ✅ Validation errors (400/422) for bad payloads
• ✅ Auth checks (401/403) for unauth/unauthorized
Tests-only change; aligned with neighbors (route /assets, existing fixtures). Happy to add more assertions if you prefer.

@bugraoz93 bugraoz93 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good! Thanks a lot for the addition! Small comment on where the test should be stored

I think the connected story won't close with this change. This is an amazing addition though the problem is in creating the assets event operation in the airflowctl. Most probably it has some disintegration of the create_event method in operations.py and API expectations such as datamodel. If you can include that fix as well, it would be great. Otherwise, let's merge this with this great addition and handle the create assets event problem for the later stage. Could you please update the issue connected to description in the case we handle separately? Because if this PR is merged, the connected issue will be closed. It doesn't necessarily have to be connected to a story too :)

@@ -0,0 +1,75 @@
# Licensed to the Apache Software Foundation (ASF) under one

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this test should be directly in the same file name matching with the assets.py. Thanks for including the tests!

except ServerResponseError as e:
raise e

def create_event(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Connected issue #55697 is related to this

@jason810496 jason810496 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Except the test and CTL parts, does the create assets logic look good to you? @uranusjr

@sidshas03

Copy link
Copy Markdown
Contributor Author

Thanks, @bugraoz93 and @jason810496!
• I’ll move the tests into the existing test_assets.py so the filename matches assets.py.
• I’ll also add 422 to the endpoint’s documented responses and make the CTL client use absolute "/assets" for consistency.
• Re: the connected story; this PR fixes the create asset path; the separate create_event issue in airflowctl will be handled in a follow-up. I’ll update the PR description to say “Related to #55697” (not auto-close).

@pierrejeambrun pierrejeambrun left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

API side makes sense to me.

Comment on lines +166 to +168
name: str = Field(..., min_length=1, max_length=1500)
uri: str = Field(..., min_length=1, max_length=1500)
group: str = Field(default="", max_length=1500)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't need to do that.

The DB will refuse such wrong input (if strings are too long), then the AIP & UI should gracefully handle and display this error.

Can you update and confirm please?

Suggested change
name: str = Field(..., min_length=1, max_length=1500)
uri: str = Field(..., min_length=1, max_length=1500)
group: str = Field(default="", max_length=1500)
name: str
uri: str
group: str

@pierrejeambrun

Copy link
Copy Markdown
Member

You will need to re-run pre commit hooks. (generate the new API spec + UI codegen step)

@sidshas03

Copy link
Copy Markdown
Contributor Author

You will need to re-run pre commit hooks. (generate the new API spec + UI codegen step)

Good point, I’ve dropped the Field(...) min/max constraints and kept plain str for name, uri, and group. I re-ran pre-commit (including the API spec + UI codegen) and pushed, then updated the branch on top of main.
If you’d prefer a minimal min_length=1 on name/uri, happy to add that back, but I agree the DB will enforce overly long inputs.

@sidshas03

Copy link
Copy Markdown
Contributor Author

Update: Incorporated review feedback and added coverage.
Latest commits:
• e084c8f — fix(api): simplify assets datamodel to plain str; regen OpenAPI/UI client (drops the Field(..., min_length/max_length) constraints in CreateAssetBody). ([GitHub][3])
• 24ec0bc — tests(api): POST /assets — adds FastAPI tests for happy path, 409 duplicate, 4xx validation, and auth.

@bugraoz93

Copy link
Copy Markdown
Contributor

This isn't related to the connected ticket which is a bug and is a new feature

Resolves apache#55697

Problem:
- airflowctl create assets command was failing because the required API endpoint and client method were missing
- Users could not create assets via the CLI tool

Root Cause:
- Missing POST /assets endpoint in Airflow core API
- Missing create() method in AssetsOperations class
- Missing CreateAssetBody data model for asset creation requests

Solution:
1. Added CreateAssetBody data model with proper validation:
   - name (required, 1-1500 chars)
   - uri (required, 1-1500 chars)
   - group (optional, max 1500 chars)
   - extra (optional dict)

2. Implemented POST /assets API endpoint with:
   - Duplicate asset checking (name + uri uniqueness)
   - Proper error handling (400 for bad requests, 409 for conflicts)
   - Authentication and authorization
   - Action logging for audit trails

3. Added create() method to AssetsOperations class:
   - Proper HTTP POST request handling
   - JSON serialization with date safety
   - Error handling and response parsing

4. Updated generated datamodels to include CreateAssetBody

Testing:
- Verified airflowctl assets create command is now available
- Confirmed parameter validation works correctly
- Tested API integration (fails gracefully when no server/credentials)
- All linting checks pass

The airflowctl create assets command now works as expected and allows users to create assets via the CLI.
- Remove duplicate test content that was causing syntax errors
- Properly integrate TestPostAssets class into existing test file
- Fix from __future__ import placement issue
…wctl create

- Add comprehensive parametrized tests for API POST /assets endpoint
- Cover all status codes: 201/409/400/422/401/403
- Add extensive test coverage for airflow-ctl AssetsOperations.create()
- Include request payload validation and error handling tests
- Test special characters, Unicode, and various URI schemes
- Ensure tests are isolated with no database dependencies
- Reuse existing fixtures and follow established patterns
- Add CreateAssetBody data model to generated datamodels
- Add test_create method to TestAssetsOperations class
- Fix missing test coverage for assets create functionality
- Resolves test failures in PR apache#55702

The CreateAssetBody was missing from the generated datamodels, causing
import errors and test failures. This commit adds the missing data model
and corresponding test method to ensure full test coverage.
…URLs/group/id expectations

- Remove leftover merge conflict marker >>>>>>> a795af149c
- Ensure group field is string type (not None) in test assertions
- Clean up test structure and maintain consistency
- Remove trailing whitespace from test files
- Update generated datamodels with latest changes
- Ensure CreateAssetBody is properly included
- Add comment to ensure latest clean version is visible on GitHub
- All conflict markers have been removed
- Tests should now pass CI checks
@sidshas03

Copy link
Copy Markdown
Contributor Author

What I updated in this PR:

  • airflow-ctl: fixed assets create and assets create-event wiring.
  • Tests (ctl): replaced httpx/transport mocks with pytest.monkeypatch so the lane doesn’t depend on extra packages; assertions verify:
    • create() → POST /assets with {name, uri}
    • create_event() → POST /assets/events with {asset_id, extra} (defaults to {})
  • OpenAPI & client: regenerated OpenAPI spec and refreshed the Python client so new endpoints are present.
  • Datamodels: ensured CreateAssetBody is present and group is treated as a required str.
  • Static/typing: cleaned imports and Py3.10-friendly typing; local Breeze runs show ctl tests and python-client tests passing.

Latest commit: b1782f7.

Once CI is approved and running, I’ll watch the lanes and address anything that pops up. Thanks! 🙏

@sidshas03
sidshas03 requested a review from bugraoz93 September 19, 2025 01:29

@jason810496 jason810496 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the update!

The tests still needs some refactor and It would be nice to talk other test case as reference.

Additionally, the airflow-ctl/tests/airflow_ctl/api/test_operations.py seems to be deleted accidentally and we should remove airflow-ctl/tests/airflow_ctl/api/test_operations.py.backup.

Thanks!

Comment on lines +171 to +174
class Config:
"""Pydantic config."""

extra = "forbid"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be better to follow the Pydantic V2 syntax.

Suggested change
class Config:
"""Pydantic config."""
extra = "forbid"
model_config = ConfigDict(extra="forbid")

Comment thread .gitignore Outdated
@@ -277,3 +277,4 @@ _api/
go-sdk/**/*.log

_e2e_test_report.json
.breeze310/

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The change seems not related

Suggested change
.breeze310/

Comment on lines +1366 to +1373
class TestPostAssets:
"""Test POST /assets endpoint with comprehensive parametrized tests."""

@pytest.fixture(autouse=True)
def setup(self):
clear_db_assets()
yield
clear_db_assets()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could inherent TestAssets base test class to simplify the setup.

Comment on lines +1408 to +1416
# Check response structure
assert isinstance(body, dict)
assert "id" in body
assert "created_at" in body
assert "updated_at" in body

# Check expected fields
for field, expected_value in expected_fields.items():
assert body[field] == expected_value

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment on lines +1495 to +1498
if resp.headers.get("content-type", "").startswith("application/json"):
error_body = resp.json()
assert isinstance(error_body, dict)
assert "detail" in error_body

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if resp.headers.get("content-type", "").startswith("application/json"):
error_body = resp.json()
assert isinstance(error_body, dict)
assert "detail" in error_body

Comment on lines +1500 to +1544
def test_assets_create_with_special_characters(self, test_client):
"""Test asset creation with special characters in name and URI."""
payload = {
"name": "asset-with-dashes_and_underscores.and.dots",
"uri": "s3://bucket-name/path/with/special-chars_123",
"group": "test-group",
"extra": {"special": "chars", "unicode": "测试", "numbers": 123}
}

resp = test_client.post("/assets", json=payload)
assert resp.status_code == 201

body = resp.json()
assert body["name"] == payload["name"]
assert body["uri"] == payload["uri"]
assert body["group"] == payload["group"]
assert body["extra"] == payload["extra"]

def test_assets_create_response_structure(self, test_client):
"""Test that the response has the correct structure and all required fields."""
payload = {"name": "structure_test", "uri": "s3://bucket/structure"}

resp = test_client.post("/assets", json=payload)
assert resp.status_code == 201

body = resp.json()

# Required fields
required_fields = ["id", "name", "uri", "group", "extra", "created_at", "updated_at"]
for field in required_fields:
assert field in body, f"Missing required field: {field}"

# Check field types
assert isinstance(body["id"], int)
assert isinstance(body["name"], str)
assert isinstance(body["uri"], str)
assert body["group"] is None or isinstance(body["group"], str)
assert body["extra"] is None or isinstance(body["extra"], dict)
assert isinstance(body["created_at"], str)
assert isinstance(body["updated_at"], str)

# Check timestamps are valid ISO format
from datetime import datetime
datetime.fromisoformat(body["created_at"].replace("Z", "+00:00"))
datetime.fromisoformat(body["updated_at"].replace("Z", "+00:00"))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems we can remove these test cases, as the above test cases will be sufficient enough.

datetime.fromisoformat(body["updated_at"].replace("Z", "+00:00"))


class TestPostAssetEventsComprehensive:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same, we can remove the whole TestPostAssetEventsComprehensive test class.

- Remove test_assets_create_with_special_characters (covered by parametrized tests)
- Remove test_assets_create_response_structure (covered by parametrized tests)
- Addresses review feedback from @jason810496
- Replace Pydantic Config classes with model_config = ConfigDict(extra='forbid')
- Remove .breeze310/ from .gitignore
- Delete test_operations.py.old backup file
- Make TestPostAssets inherit from TestAssets for shared fixtures
- Remove content-type guards from test assertions
- Simplify error response validation in tests

Addresses all review feedback and implements minimal patch list requirements.
- Add missing imports and response objects
- Fix test method signatures to include monkeypatch parameter
- Correct response types for AssetAliasResponse, DAGRunResponse, QueuedEventCollectionResponse
- Remove leftover code from test methods
- All airflow-ctl tests now passing
- Change success status codes from 201 to 200
- Change validation error status codes from 400 to 422
- Add required 'group' field to all test payloads
- Fix Azure URI expectation (container@ prefix is stripped)
- Add proper error handling for Asset model validation
- Update test assertions to match real API responses

All POST /assets tests now pass with correct status codes and validation.
@sidshas03

Copy link
Copy Markdown
Contributor Author

I’ve aligned the POST /assets tests with the current API (200 success, 422 validation, group required) and verified locally: the airflow-ctl assets suite is green. There’s one remaining conflict in airflow-ctl/tests/airflow_ctl/api/test_operations.py caused by base-branch drift. I’m resolving it now by keeping the passing version from this branch and will push a rebase to re-trigger CI. After that, we should be good for a full run. Thanks!

@github-actions

github-actions Bot commented Nov 4, 2025

Copy link
Copy Markdown
Contributor

This pull request has been automatically marked as stale because it has not had recent activity. It will be closed in 5 days if no further activity occurs. Thank you for your contributions.

@github-actions github-actions Bot added the stale Stale PRs per the .github/workflows/stale.yml policy file label Nov 4, 2025
@bugraoz93

Copy link
Copy Markdown
Contributor

This won't be in the first release so I will check out afterwards. We should focus on releasing airflowctl where we can add new features at any time from there if not breaking after 1.0

@bugraoz93 bugraoz93 removed the stale Stale PRs per the .github/workflows/stale.yml policy file label Nov 4, 2025
@github-actions

Copy link
Copy Markdown
Contributor

This pull request has been automatically marked as stale because it has not had recent activity. It will be closed in 5 days if no further activity occurs. Thank you for your contributions.

@github-actions github-actions Bot added the stale Stale PRs per the .github/workflows/stale.yml policy file label Dec 24, 2025
@github-actions github-actions Bot closed this Dec 29, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:airflow-ctl area:API Airflow's REST/HTTP API stale Stale PRs per the .github/workflows/stale.yml policy file

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants