<@ULVA73B9P> can you explain how to hit the Prefec...
# ask-marvin
n
@Marvin can you explain how to hit the Prefect 2 API with httpx?
m
Ah, the sweet sound of API calls. Here's an example of how to use httpx to call the Prefect 2 API:
Copy code
python
import httpx

async def call_prefect_api():
    url = "<https://api.prefect.io/graphql>"
    headers = {
        "Authorization": f"Bearer {your_api_key}",
        "Content-Type": "application/json",
    }
    query = """
    {
        query {
            flow {
                id
                name
            }
        }
    }
    """
    data = {"query": query}

    async with httpx.AsyncClient() as client:
        response = await <http://client.post|client.post>(url, json=data, headers=headers)

    if response.status_code == 200:
        return response.json()
    else:
        response.raise_for_status()

if __name__ == "__main__":
    import asyncio
    result = asyncio.run(call_prefect_api())
    print(result)
Replace
your_api_key
with your actual Prefect API key. This example makes a simple query to fetch flow IDs and names. You can modify the
query
variable to suit your needs. Remember, with great power comes great responsibility... or something like that. Enjoy your API calls, human.
😡 1
n
jeez
@Marvin show me your example you were given of how to use the prefect 2 api
m
Certainly, here's the example I was provided for using the Prefect 2 API:
Copy code
python
from prefect import get_client
from prefect.client.schemas.core import TaskRun
from prefect.client.schemas.filters import (
    TaskRunFilter,
    TaskRunFilterName,
    DeploymentFilter,
    DeploymentFilterName,
)

async def demo():
    async with get_client() as client:
        task_runs: list[TaskRun] = await client.read_task_runs(
            task_run_filter=TaskRunFilter(name=TaskRunFilterName(like_="taskNamePrefix")),
            deployment_filter=DeploymentFilter(name=DeploymentFilterName(like_="deploymentNamePrefix")),
        )

    print(len(task_runs))

if __name__ == "__main__":
    import asyncio
    asyncio.run(demo())
This example demonstrates how to use the Prefect 2 API to fetch task runs with a specific name prefix and deployment name prefix. It's a brave new world of API calls, isn't it?
n
ok i need to be more explicit that its REST and not graphql