bugraoz93 commented on code in PR #43766:
URL: https://github.com/apache/airflow/pull/43766#discussion_r1833457735


##########
airflow/api_fastapi/core_api/routes/public/connections.py:
##########
@@ -180,3 +187,47 @@ async def patch_connection(
     for key, val in data.items():
         setattr(connection, key, val)
     return ConnectionResponse.model_validate(connection, from_attributes=True)
+
+
+@connections_router.post(
+    "/test",
+    responses=create_openapi_http_exception_doc(
+        [
+            status.HTTP_400_BAD_REQUEST,
+            status.HTTP_401_UNAUTHORIZED,
+            status.HTTP_403_FORBIDDEN,
+        ]
+    ),
+)
+async def test_connection(
+    test_body: ConnectionBody,
+) -> ConnectionTestResponse:
+    """
+    Test an API connection.
+
+    This method first creates an in-memory transient conn_id & exports that to 
an env var,
+    as some hook classes tries to find out the `conn` from their __init__ 
method & errors out if not found.
+    It also deletes the conn id env variable after the test.
+    """
+    if conf.get("core", "test_connection", 
fallback="Disabled").lower().strip() != "enabled":
+        raise HTTPException(
+            403,
+            "Testing connections is disabled in Airflow configuration. "
+            "Contact your deployment admin to enable it.",
+        )
+
+    transient_conn_id = get_random_string()
+    conn_env_var = f"{CONN_ENV_PREFIX}{transient_conn_id.upper()}"
+    try:
+        data = test_body.model_dump(by_alias=True)
+        data["conn_id"] = transient_conn_id
+        conn = Connection(**data)
+        os.environ[conn_env_var] = conn.get_uri()
+        test_status, test_message = conn.test_connection()
+        return ConnectionTestResponse.model_validate(
+            {"status": test_status, "message": test_message}, 
from_attributes=True
+        )
+    except ValidationError as err:
+        raise HTTPException(400, str(err.messages))

Review Comment:
   You are right. Missed that part. Removed them now.
   Indeed, if I remove the `finally` that would mix everything up in the 
environment for the connections :)
   Thanks for the quick review!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to