Hi all, How do you authenticate to the Prefect Gr...
# ask-community
j
Hi all, How do you authenticate to the Prefect GraphQL API using only Python's
requests
library? I need to cancel a bunch of flow runs but the Web interface is too cumbersome and the CLI tool doesn't support cancellation. I notice that the browser has a token that only lasts a few minutes.
k
Hey, it will be like this:
Copy code
query = """query {flow{ name, id}}"""


url = '<https://api.prefect.io>'
r = <http://requests.post|requests.post>(url, json={'query': query}, headers={"authorization": "Bearer MY_TOKEN_HERE"})
print(r.status_code)
print(r.text)
j
How do you renew the frequently-expiring token?
My existing code is similar to what you suggested, but I have to manually extract the token from my browser every time I use it.
k
How did you handle it with the Prefect Client when not using the requests library? Yeah you’d need to extract it from somewhere it seems.
j
The Prefect CLI client has no cancellation functionality. The only other way to do it is to use the embedded GraphiQL interface in the Web console.
The Prefect CLI client doesn't require me to extract a token using my browser's debugging tools, so there must be a solution to this problem.
k
We can open a ticket for a feature request here, but just to clarify the ask, you want to be able to revoke tokens via the CLI?
j
No. I want to be able to cancel flow runs via the CLI.
k
What is stopping you from using the GraphQL client?
client.graphql(query)
and cancel that way in a Python script?
j
I didn't realize the client supported raw GraphQL. All the documentation I saw talked about a Python API that mirrors a subset of the GraphQL one. I ran into things that I needed to do that weren't mirrored in the Python API and gave up.
k
Ah ok the CLI really just hits the API under the hood. The
client.graphql
is in the API here
Sample:
Copy code
response = client.graphql(
        f"""
        query {{ 
          flow_run_by_pk ( id: "{flow_run_id}" ),
        {{ 
            id, 
            flow {{
              id,
              name,
              version
            }}
            state,
            start_time,
            end_time,
            state_message 
            task_runs {{
              id, 
              state, 
              state_message,
              start_time,
              end_time,
              task {{
                id,
                name,
                slug,
                type
              }}
            }}
          }}
        }}"""
    )
j
I see there's now a
prefect.client.client.Client.cancel_flow_run
Python function. I'm not sure if that was there before, or if it's in the version of Prefect I'm using.
👍 1
I have to do a lot of scrolling to see the
prefect.client.client.Client.graphql
function. No wonder I didn't see it before.