### Install Dependencies and Setup Environment Source: https://github.com/policyengine/policyengine-api/blob/master/README.md These make commands install project dependencies and set up the local development environment. Ensure you have a Python virtual environment activated before running. ```bash make install make setup-env ``` -------------------------------- ### Start Redis Server Source: https://github.com/policyengine/policyengine-api/blob/master/README.md To test features requiring Redis or service workers, you need to install and start a Redis server. This example uses Homebrew to install and then start Redis. ```bash brew install redis redis-server ``` -------------------------------- ### Start Local Development Server Source: https://github.com/policyengine/policyengine-api/blob/master/README.md Run this command to start a local development server for the PolicyEngine API. This allows you to see your changes in real-time. ```bash make debug ``` -------------------------------- ### Test API Endpoint Locally Source: https://github.com/policyengine/policyengine-api/blob/master/README.md Send a GET request to this URL using a tool like Postman to verify that the local API server is running correctly. This example targets endpoint /us/policy/2. ```http http://127.0.0.1:5001/us/policy/2 ``` -------------------------------- ### Run PolicyEngine API for Calculations Source: https://github.com/policyengine/policyengine-api/blob/master/README.md This command starts the PolicyEngine API server with debug mode enabled, necessary for running calculations that utilize Redis or service workers. ```bash FLASK_DEBUG=1 python -m flask --app policyengine_api.api run ``` -------------------------------- ### Configure PolicyEngine App API URL Source: https://github.com/policyengine/policyengine-api/blob/master/README.md When testing in combination with policyengine-app, update the API URL in `policyengine-app/src/api/call.js` to point to your local development server. This example sets it to http://127.0.0.1:5001. ```javascript const POLICYENGINE_API = "http://127.0.0.1:5001" ``` -------------------------------- ### Compute Household Under Policy (Stored) Source: https://context7.com/policyengine/policyengine-api/llms.txt Runs a full tax-benefit calculation for a stored household under a specific policy. The results are cached and include all output variables for every person and entity group. Two examples show baseline calculation and calculation under a reform policy. ```bash # Baseline (current law = policy ID 2 for the US) curl "https://api.policyengine.org/us/household/12345/policy/2" ``` ```bash # Under reform policy 67890 curl "https://api.policyengine.org/us/household/12345/policy/67890" ``` -------------------------------- ### Configure Debug Server Port Source: https://github.com/policyengine/policyengine-api/blob/master/README.md If you encounter port conflicts, modify the Makefile to specify a different port for the debug server. This example sets the port to 5001. ```makefile debug: FLASK_APP=policyengine_api.api FLASK_DEBUG=1 flask run --without-threads --port=5001 ``` -------------------------------- ### Retrieve Policy by ID Source: https://context7.com/policyengine/policyengine-api/llms.txt Fetches stored policy data using its unique ID. This GET request retrieves all details associated with a specific policy. ```bash curl https://api.policyengine.org/us/policy/67890 ``` -------------------------------- ### Configure CORS for Development Source: https://github.com/policyengine/policyengine-api/blob/master/README.md To resolve CORS errors during development, modify the CORS configuration in `api.py`. This example allows all origins. ```python CORS(app, resources={r"/*": {"origins": "*"}}) ``` -------------------------------- ### Get User's Saved Policies Source: https://context7.com/policyengine/policyengine-api/llms.txt Returns all policy pairs saved by a given user, identified by their `user_id`. The response includes details for each saved policy. ```bash curl https://api.policyengine.org/us/user-policy/42 ``` -------------------------------- ### Update Starter Docker Image Source: https://github.com/policyengine/policyengine-api/blob/master/gcp/README.md Follow these steps to build and upload the Python package, then build and push the updated Docker image. ```bash python setup.py sdist ``` ```bash twine upload dist/* ``` ```bash cd gcp ``` ```bash docker build . ``` ```bash docker images ``` ```bash docker tag policyengine/policyengine-api ``` ```bash docker push policyengine/policyengine-api ``` -------------------------------- ### GET /{country_id}/report/{report_id} Source: https://context7.com/policyengine/policyengine-api/llms.txt Fetches a report output record by ID, including its status and any computed output. ```APIDOC ## GET /{country_id}/report/{report_id} ### Description Fetches a report output record by ID, including its status and any computed output. ### Method GET ### Endpoint `/{country_id}/report/{report_id}` ### Parameters #### Path Parameters - **report_id** (integer) - Required - The ID of the report output to retrieve. ### Response #### Success Response (200) - **status** (string) - Indicates the status of the operation ('ok' or 'error'). - **message** (string) - A message describing the result of the operation. - **result** (object) - Contains the details of the report output record, including its ID, status, and computed output. #### Response Example ```json { "status": "ok", "message": null, "result": { "id": 300, "status": "complete", "output": { ... } } } ``` ``` -------------------------------- ### Clone PolicyEngine API Repository Source: https://github.com/policyengine/policyengine-api/blob/master/README.md Use this command to clone the PolicyEngine API repository to your local machine. This is the first step for contributing to the project. ```bash git clone https://github.com/PolicyEngine/policyengine-api.git ``` -------------------------------- ### Create User Profile Source: https://context7.com/policyengine/policyengine-api/llms.txt Creates a new user profile record keyed on an Auth0 ID. Requires authentication details and basic user information. ```bash curl -s -X POST https://api.policyengine.org/us/user-profile \ -H "Content-Type: application/json" \ -d '{ "auth0_id": "auth0|abc123", "username": "jane_doe", "user_since": "2024-01-15" }' ``` -------------------------------- ### Check API Home Page Source: https://context7.com/policyengine/policyengine-api/llms.txt Use this endpoint as a liveness smoke-test to verify the API is running. ```bash curl https://api.policyengine.org/ ``` -------------------------------- ### Stateless Household Calculation with Defaults Source: https://context7.com/policyengine/policyengine-api/llms.txt Use this endpoint for stateless household calculations where all missing yearly variables should be filled with their default values before computation. This ensures no variable remains null in the output. ```bash curl -s -X POST https://api.policyengine.org/us/calculate-full \ -H "Content-Type: application/json" \ -d '{ "household": { "people": { "you": { "age": { "2024": 35 }, "employment_income": { "2024": 80000 } } }, "tax_units": { "your tax unit": { "members": ["you"] } }, "families": { "your family": { "members": ["you"] } }, "marital_units":{"your marital unit":{ "members": ["you"] } }, "households": { "your household": { "members": ["you"], "state_name": { "2024": "TX" } } }, "spm_units": { "your household": { "members": ["you"] } } }, "policy": {} }' # Returns full result with all derived variables populated ``` -------------------------------- ### Run Automated Tests Source: https://github.com/policyengine/policyengine-api/blob/master/README.md Execute the project's automated tests using the make debug-test command. Note that `make test` is reserved for production use and requires database credentials. ```bash make debug-test ``` -------------------------------- ### Create Report Output Record Source: https://context7.com/policyengine/policyengine-api/llms.txt Creates a new report output record to tie simulation IDs together for comparison reports. Requires simulation IDs and a year. ```bash curl -s -X POST https://api.policyengine.org/us/report \ -H "Content-Type: application/json" \ -d '{ "simulation_1_id": 500, "simulation_2_id": 501, "year": "2024" }' # { "status": "ok", "message": "Report output created successfully", # "result": { "id": 300, "status": "pending", ... } } ``` -------------------------------- ### Create Simulation Record Source: https://context7.com/policyengine/policyengine-api/llms.txt Creates a new simulation record linking a population to a policy. Returns an existing record if one already exists for the same parameters. Requires population details and policy ID. ```bash curl -s -X POST https://api.policyengine.org/us/simulation \ -H "Content-Type: application/json" \ -d '{ "population_id": "12345", "population_type": "household", "policy_id": 67890 }' ``` -------------------------------- ### Home Page Source: https://context7.com/policyengine/policyengine-api/llms.txt Returns the HTML home page of the API, useful as a liveness smoke-test. ```APIDOC ## GET / ### Description Returns the HTML home page of the API, useful as a liveness smoke-test. ### Method GET ### Endpoint / ### Request Example ```bash curl https://api.policyengine.org/ ``` ### Response Example ``` HTML string with API welcome page ``` ``` -------------------------------- ### Format Code with Black Source: https://github.com/policyengine/policyengine-api/blob/master/README.md Automatically format your code to adhere to project standards using the make format command. This step ensures code consistency before submitting a pull request. ```bash make format ``` -------------------------------- ### Retrieve Simulation Source: https://context7.com/policyengine/policyengine-api/llms.txt Fetches a simulation record by its ID. Includes the current status and output of the simulation. ```bash curl https://api.policyengine.org/us/simulation/500 ``` -------------------------------- ### Create Policy Table SQL Source: https://github.com/policyengine/policyengine-api/blob/master/policyengine_api/data/README.md SQL statement to create the 'policy' table if it does not exist. This table stores policy definitions and their parameters. ```sql CREATE TABLE IF NOT EXISTS policy ( id SERIAL PRIMARY KEY, label VARCHAR(255) NOT NULL, version VARCHAR(255) NOT NULL, policy_json JSONB NOT NULL ); ``` -------------------------------- ### Simulation Management Source: https://context7.com/policyengine/policyengine-api/llms.txt APIs for creating, retrieving, and updating simulations. ```APIDOC ## `POST /{country_id}/simulation` — Create a simulation record ### Description Creates a new simulation record linking a population (household or geography) to a policy. Returns the existing record if one already exists for the same parameters. ### Method POST ### Endpoint `/{country_id}/simulation` ### Request Body - **population_id** (string) - Required - The ID of the population. - **population_type** (string) - Required - The type of the population (e.g., 'household', 'geography'). - **policy_id** (integer) - Required - The ID of the policy. ### Request Example ```json { "population_id": "12345", "population_type": "household", "policy_id": 67890 } ``` ### Response #### Success Response (200) - **status** (string) - The status of the request. - **message** (string) - A message describing the result. - **result** (object) - The created simulation record details. ## `GET /{country_id}/simulation/{simulation_id}` — Retrieve a simulation ### Description Fetches a simulation record by ID, including its current status and output. ### Method GET ### Endpoint `/{country_id}/simulation/{simulation_id}` ### Response #### Success Response (200) - **status** (string) - The status of the request. - **message** (string | null) - A message describing the result. - **result** (object) - The simulation record details. ## `PATCH /{country_id}/simulation` — Update simulation status/output ### Description Used by worker processes to write back results or errors into a simulation record. ### Method PATCH ### Endpoint `/{country_id}/simulation` ### Request Body - **id** (integer) - Required - The ID of the simulation to update. - **status** (string) - Optional - The new status of the simulation. - **output** (object) - Optional - The output of the simulation. - **api_version** (string) - Optional - The API version used. ### Request Example ```json { "id": 500, "status": "complete", "output": { "household_net_income": { "2024": 55000 } }, "api_version": "1.653.3" } ``` ### Response #### Success Response (200) - **status** (string) - The status of the request. - **message** (string) - A message describing the result. - **result** (object) - The updated simulation record details. ``` -------------------------------- ### Retrieve User Profile Source: https://context7.com/policyengine/policyengine-api/llms.txt Fetches a user profile by `auth0_id` or `user_id` query parameter. Use `auth0_id` for direct lookup or `user_id` for internal references. ```bash curl "https://api.policyengine.org/us/user-profile?auth0_id=auth0|abc123" ``` ```bash curl "https://api.policyengine.org/us/user-profile?user_id=42" ``` -------------------------------- ### Create Economy Table SQL Source: https://github.com/policyengine/policyengine-api/blob/master/policyengine_api/data/README.md SQL statement to create the 'economy' table if it does not exist. This table stores the results of microsimulation runs for households under specific policies. ```sql CREATE TABLE IF NOT EXISTS economy ( household_id INT NOT NULL, policy_id INT NOT NULL, version VARCHAR(255) NOT NULL, economy_json JSONB NOT NULL, PRIMARY KEY (household_id, policy_id) ); ``` -------------------------------- ### Create Household Table SQL Source: https://github.com/policyengine/policyengine-api/blob/master/policyengine_api/data/README.md SQL statement to create the 'household' table if it does not exist. This table stores individual household data. ```sql CREATE TABLE IF NOT EXISTS household ( id SERIAL PRIMARY KEY, label VARCHAR(255) NOT NULL, version VARCHAR(255) NOT NULL, household_json JSONB NOT NULL ); ``` -------------------------------- ### Create Household Source: https://context7.com/policyengine/policyengine-api/llms.txt Persists a new household JSON record and returns a stable `household_id`. Household data must be provided under the `"data"` key. ```APIDOC ## POST /{country_id}/household — Create household ### Description Persists a new household JSON record and returns a stable `household_id`. Household data must be provided under the `"data"` key. ### Method POST ### Endpoint /{country_id}/household ### Parameters #### Path Parameters - **country_id** (string) - Required - The identifier for the country (e.g., `us`, `uk`, `ca`, `ng`, `il`). #### Request Body - **data** (object) - Required - Contains the household's demographic and financial information. - **people** (object) - Defines individuals in the household. - **tax_units** (object) - Defines tax units within the household. - **families** (object) - Defines families within the household. - **marital_units** (object) - Defines marital units within the household. - **households** (object) - Defines the household structure and state. - **spm_units** (object) - Defines the Supplemental Poverty Measure units. ### Request Example ```bash # Create a US household (single adult, age 40, $40k employment income) curl -s -X POST https://api.policyengine.org/us/household \ -H "Content-Type: application/json" \ -d '{ "data": { "people": { "you": { "age": { "2024": 40 }, "employment_income": { "2024": 40000 } } }, "tax_units": { "your tax unit": { "members": ["you"] } }, "families": { "your family": { "members": ["you"] } }, "marital_units":{ "your marital unit":{ "members": ["you"] } }, "households": { "your household": { "members": ["you"], "state_name": { "2024": "CA" } } }, "spm_units": { "your household": { "members": ["you"] } } } }' ``` ### Response Example ```json { "status": "ok", "message": null, "result": { "household_id": 12345 } } ``` ``` -------------------------------- ### Retrieve OpenAPI Specification Source: https://context7.com/policyengine/policyengine-api/llms.txt Fetches the full OpenAPI 3.0 specification for the API in JSON format, including version details. Useful for understanding the API's structure and capabilities. ```bash curl https://api.policyengine.org/specification | python3 -m json.tool | head -20 # { # "openapi": "3.0.0", # "info": { "title": "PolicyEngine API", "version": "3.40.8", ... }, # "paths": { ... } # } ``` -------------------------------- ### Stateless Household Calculation with Defaults Source: https://context7.com/policyengine/policyengine-api/llms.txt Performs a stateless household calculation, automatically filling in missing yearly variables with their default values before computation. This ensures all variables are populated in the output. ```APIDOC ## `POST /{country_id}/calculate-full` — Stateless household calculation with defaults Same as `/calculate` but automatically fills in all missing yearly variables with their default values before computing, ensuring no variable is left as `null` in the output. ### Method POST ### Endpoint `/{country_id}/calculate-full` ### Request Body - **household** (object) - Required - Household data including people, tax units, families, etc. - **policy** (object) - Required - Policy details to apply. ### Request Example ```json { "household": { "people": { "you": { "age": { "2024": 35 }, "employment_income": { "2024": 80000 } } }, "tax_units": { "your tax unit": { "members": ["you"] } }, "families": { "your family": { "members": ["you"] } }, "marital_units":{ "your marital unit":{ "members": ["you"] } }, "households": { "your household": { "members": ["you"], "state_name": { "2024": "TX" } } }, "spm_units": { "your household": { "members": ["you"] } } }, "policy": {} } ``` ### Response #### Success Response (200) Returns full result with all derived variables populated. ``` -------------------------------- ### Create or Retrieve Policy Source: https://context7.com/policyengine/policyengine-api/llms.txt This endpoint stores a policy reform as a JSON map. If an identical policy exists, its ID is returned; otherwise, a new policy is created and its ID is returned with a 201 status. Use POST with Content-Type set to application/json. ```bash # Create a US policy that raises the IRS personal exemption amount curl -s -X POST https://api.policyengine.org/us/policy \ -H "Content-Type: application/json" \ -d '{ "label": "Raise IRS exemption to $10k", "data": { "gov.irs.income.exemption.amount": { "2024-01-01.2030-12-31": 10000 } } }' ``` -------------------------------- ### User Profile Management Source: https://context7.com/policyengine/policyengine-api/llms.txt APIs for creating, retrieving, and updating user profiles. ```APIDOC ## `POST /{country_id}/user-profile` — Create user profile ### Description Creates a new user profile record keyed on an Auth0 ID. ### Method POST ### Endpoint `/{country_id}/user-profile` ### Request Body - **auth0_id** (string) - Required - The Auth0 ID of the user. - **username** (string) - Required - The username of the user. - **user_since** (string) - Required - The date the user account was created. ### Request Example ```json { "auth0_id": "auth0|abc123", "username": "jane_doe", "user_since": "2024-01-15" } ``` ### Response #### Success Response (200) - **status** (string) - The status of the request. - **message** (string) - A message describing the result. - **result** (object) - The created user profile details. ## `GET /{country_id}/user-profile` — Retrieve user profile ### Description Fetches a user profile by `auth0_id` or `user_id` query parameter. ### Method GET ### Endpoint `/{country_id}/user-profile` ### Query Parameters - **auth0_id** (string) - Optional - The Auth0 ID of the user. - **user_id** (integer) - Optional - The user ID of the user. ### Response #### Success Response (200) - **status** (string) - The status of the request. - **message** (string) - A message describing the result. - **result** (object) - The user profile details. ## `PUT /{country_id}/user-profile` — Update user profile ### Description Updates mutable fields (`username`, `primary_country`, `user_since`) for a given `user_id`. ### Method PUT ### Endpoint `/{country_id}/user-profile` ### Request Body - **user_id** (integer) - Required - The ID of the user to update. - **username** (string) - Optional - The new username for the user. - **primary_country** (string) - Optional - The new primary country for the user. - **user_since** (string) - Optional - The new user since date. ### Request Example ```json { "user_id": 42, "username": "jane_smith", "primary_country": "uk" } ``` ### Response #### Success Response (200) - **status** (string) - The status of the request. - **message** (string) - A message describing the result. - **result** (object) - The updated user profile details. ``` -------------------------------- ### OpenAPI Specification Source: https://context7.com/policyengine/policyengine-api/llms.txt Returns the full OpenAPI 3.0 specification for the API as JSON, including the current version number. ```APIDOC ## GET /specification — OpenAPI specification ### Description Returns the full OpenAPI 3.0 specification for the API as JSON, including the current version number. ### Method GET ### Endpoint /specification ### Request Example ```bash curl https://api.policyengine.org/specification | python3 -m json.tool | head -20 ``` ### Response Example ```json { "openapi": "3.0.0", "info": { "title": "PolicyEngine API", "version": "3.40.8", ... }, "paths": { ... } } ``` ``` -------------------------------- ### Create Household Record Source: https://context7.com/policyengine/policyengine-api/llms.txt Persists a new household JSON record to the API and returns a unique `household_id`. Ensure household data is provided under the 'data' key. ```bash # Create a US household (single adult, age 40, $40k employment income) curl -s -X POST https://api.policyengine.org/us/household \ -H "Content-Type: application/json" \ -d '{ \ "data": { \ "people": { \ "you": { \ "age": { "2024": 40 }, \ "employment_income": { "2024": 40000 } \ } \ }, \ "tax_units": { "your tax unit": { "members": ["you"] } }, \ "families": { "your family": { "members": ["you"] } }, \ "marital_units":{ "your marital unit":{ "members": ["you"] } }, \ "households": { "your household": { "members": ["you"], "state_name": { "2024": "CA" } } }, \ "spm_units": { "your household": { "members": ["you"] } } \ } \ }' # { "status": "ok", "message": null, "result": { "household_id": 12345 } } ``` -------------------------------- ### Changelog Entry Format Source: https://github.com/policyengine/policyengine-api/blob/master/README.md Structure your changelog entries in YAML format. Specify the type of change (bump) and a list of changes categorized by type (added, removed, changed, fixed). ```yaml - bump: {major, minor, patch} changes: {added, removed, changed, fixed}: - ``` -------------------------------- ### Compute household under policy Source: https://context7.com/policyengine/policyengine-api/llms.txt Runs the full tax-benefit calculation for a stored household under a stored policy and caches the result. Requires country ID, household ID, and policy ID. ```APIDOC ## GET /{country_id}/household/{household_id}/policy/{policy_id} ### Description Runs the full tax-benefit calculation for a stored household under a stored policy and caches the result locally. Returns every output variable for every person and entity group in the household. ### Method GET ### Endpoint `/{country_id}/household/{household_id}/policy/{policy_id}` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. - **message** (string) - Null or a message about the operation. - **result** (object) - Contains the calculation results for people, households, etc. ``` -------------------------------- ### Generate Named AI Prompt Source: https://context7.com/policyengine/policyengine-api/llms.txt Returns the fully-rendered text of a named prompt template filled with supplied data. Useful for debugging or for clients that want to call the LLM themselves. ```APIDOC ## `POST /{country_id}/ai-prompts/{prompt_name}` — Generate a named AI prompt ### Description Returns the fully-rendered text of a named prompt template (e.g. `simulation_analysis`) filled with the supplied data, without actually invoking the LLM. Useful for debugging or for clients that want to call the LLM themselves. ### Method POST ### Endpoint `/{country_id}/ai-prompts/{prompt_name}` ### Request Body - **currency** (string) - Required - The currency to use for the prompt. - **selected_version** (string) - Required - The version of the policy engine to use. - **time_period** (string) - Required - The time period for the simulation. - **region** (string) - Required - The region for the simulation. - **dataset** (object | null) - Optional - The dataset to use for the prompt. - **policy_label** (string) - Required - The label of the policy. - **policy** (object) - Required - The policy details. - **impact** (object) - Required - The impact of the policy. - **relevant_parameters** (array) - Required - List of relevant parameters. - **relevant_parameter_baseline_values** (array) - Required - List of relevant parameter baseline values. ### Request Example ```json { "currency": "USD", "selected_version": "1.653.3", "time_period": "2024", "region": "us", "dataset": null, "policy_label": "Raise IRS exemption", "policy": { "gov.irs.income.exemption.amount": { "2024-01-01.2030-12-31": 10000 } }, "impact": { "budget": { "budgetary_impact": -12500000000 } }, "relevant_parameters": [], "relevant_parameter_baseline_values": [] } ``` ### Response #### Success Response (200) - **status** (string) - The status of the request. - **message** (string | null) - A message describing the result. - **result** (string) - The rendered text of the AI prompt. ``` -------------------------------- ### Generate Named AI Prompt Source: https://context7.com/policyengine/policyengine-api/llms.txt Returns the rendered text of a named prompt template filled with supplied data. Useful for debugging or for clients that want to call the LLM themselves. ```bash curl -s -X POST https://api.policyengine.org/us/ai-prompts/simulation_analysis \ -H "Content-Type: application/json" \ -d '{ "currency": "USD", "selected_version": "1.653.3", "time_period": "2024", "region": "us", "dataset": null, "policy_label": "Raise IRS exemption", "policy": { "gov.irs.income.exemption.amount": { "2024-01-01.2030-12-31": 10000 } }, "impact": { "budget": { "budgetary_impact": -12500000000 } }, "relevant_parameters": [], "relevant_parameter_baseline_values": [] }' ``` -------------------------------- ### AI Explanation of a Variable Trace Source: https://context7.com/policyengine/policyengine-api/llms.txt Provides an AI-generated natural-language explanation of how a specific variable's value was computed for a stored household and policy. Returns streaming NDJSON. Requires a household ID, policy ID, and variable name. ```bash curl -s -X POST https://api.policyengine.org/us/tracer-analysis \ -H "Content-Type: application/json" \ -d '{ "household_id": 12345, "policy_id": 2, "variable": "income_tax" }' \ --no-buffer # Streaming NDJSON: # {"content": "Your income tax of $4,522 is calculated as follows..."} # {"content": " First, taxable income is determined by subtracting the standard deduction..."} ``` -------------------------------- ### POST /{country_id}/report Source: https://context7.com/policyengine/policyengine-api/llms.txt Creates a new report output record that ties one or two simulation IDs together for a given year, enabling comparison reports. ```APIDOC ## POST /{country_id}/report ### Description Creates a new report output record that ties one or two simulation IDs together for a given year, enabling comparison reports. ### Method POST ### Endpoint `/{country_id}/report` ### Parameters #### Request Body - **simulation_1_id** (integer) - Required - The ID of the first simulation. - **simulation_2_id** (integer) - Optional - The ID of the second simulation for comparison. - **year** (string) - Required - The year for which the report is generated. ### Request Example ```json { "simulation_1_id": 500, "simulation_2_id": 501, "year": "2024" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the status of the operation ('ok' or 'error'). - **message** (string) - A message describing the result of the operation. - **result** (object) - Contains the details of the created report output record, including its ID and status. #### Response Example ```json { "status": "ok", "message": "Report output created successfully", "result": { "id": 300, "status": "pending" } } ``` ``` -------------------------------- ### Save Policy to User's List Source: https://context7.com/policyengine/policyengine-api/llms.txt Associates a reform/baseline policy pair with a user account for later retrieval. Includes details like policy IDs, labels, and budgetary impact. ```bash curl -s -X POST https://api.policyengine.org/us/user-policy \ -H "Content-Type: application/json" \ -d '{ "user_id": 42, "reform_id": 67890, "reform_label": "Raise IRS exemption to $10k", "baseline_id": 2, "baseline_label": "Current law", "year": "2024", "geography": "us", "number_of_provisions": 1, "api_version": "1.653.3", "added_date": "2024-06-01", "updated_date": "2024-06-01", "budgetary_impact": -12500000000 }' ``` -------------------------------- ### Stateless Household Calculation Source: https://context7.com/policyengine/policyengine-api/llms.txt This lightweight endpoint computes household and policy results without persisting any data. It accepts household and policy JSON directly in the request body, making it ideal for interactive tools and prototyping. Use POST with Content-Type set to application/json. ```bash curl -s -X POST https://api.policyengine.org/us/calculate \ -H "Content-Type: application/json" \ -d '{ "household": { "people": { "you": { "age": { "2024": 40 }, "employment_income": { "2024": 60000 } } }, "tax_units": { "your tax unit": { "members": ["you"] } }, "families": { "your family": { "members": ["you"] } }, "marital_units":{ "your marital unit":{ "members": ["you"] } }, "households": { "your household": { "members": ["you"], "state_name": { "2024": "NY" } } }, "spm_units": { "your household": { "members": ["you"] } } }, "policy": { "gov.irs.income.exemption.amount": { "2024-01-01.2030-12-31": 10000 } } }' ``` -------------------------------- ### Stateless household calculation Source: https://context7.com/policyengine/policyengine-api/llms.txt Accepts household and policy JSON inline and computes results without persisting any data. Ideal for interactive tools and prototyping. ```APIDOC ## POST /{country_id}/calculate ### Description Lightweight endpoint that accepts household and policy JSON inline and computes results without persisting anything. Ideal for interactive tools and prototyping. ### Method POST ### Endpoint `/{country_id}/calculate` ### Request Body - **household** (object) - Required - The household data for the calculation. - **policy** (object) - Required - The policy data for the calculation. ### Request Example ```json { "household": { "people": { "you": { "age": { "2024": 40 }, "employment_income": { "2024": 60000 } } }, "tax_units": { "your tax unit": { "members": ["you"] } }, "families": { "your family": { "members": ["you"] } }, "marital_units":{ "your marital unit":{ "members": ["you"] } }, "households": { "your household": { "members": ["you"], "state_name": { "2024": "NY" } } }, "spm_units": { "your household": { "members": ["you"] } } }, "policy": { "gov.irs.income.exemption.amount": { "2024-01-01.2030-12-31": 10000 } } } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. - **message** (string) - Null or a message about the operation. - **result** (object) - Contains the calculation results for people, households, etc. ``` -------------------------------- ### AI Explanation of a Variable Trace Source: https://context7.com/policyengine/policyengine-api/llms.txt Generates a natural-language explanation of how a specific variable's value was computed by running a calculation trace and using an AI model. Returns streaming NDJSON. ```APIDOC ## `POST /{country_id}/tracer-analysis` — AI explanation of a variable trace Given a stored household, a stored policy, and a variable name, this endpoint runs a calculation trace (showing all intermediate variable dependencies) and uses Claude to produce a natural-language explanation of how the final value was computed. Returns streaming NDJSON. ### Method POST ### Endpoint `/{country_id}/tracer-analysis` ### Parameters #### Path Parameters - **country_id** (string) - Required - The country identifier (e.g., `us`, `uk`). #### Request Body - **household_id** (integer) - Required - The ID of the stored household. - **policy_id** (integer) - Required - The ID of the stored policy. - **variable** (string) - Required - The name of the variable to trace and explain. ### Request Example ```bash curl -s -X POST https://api.policyengine.org/us/tracer-analysis \ -H "Content-Type: application/json" \ -d '{ "household_id": 12345, "policy_id": 2, "variable": "income_tax" }' \ --no-buffer ``` ### Response Streaming NDJSON lines, each a JSON object with a "content" key containing the next chunk of the AI-generated explanation. ``` -------------------------------- ### Retrieve Household Data by ID Source: https://context7.com/policyengine/policyengine-api/llms.txt Fetches stored household input data using its unique identifier. This endpoint retrieves the complete household JSON record. ```bash curl https://api.policyengine.org/us/household/12345 # { # "status": "ok", # "message": null, # "result": { # "id": 12345, # "country_id": "us", # "household_json": { ... }, # "household_hash": "abc123", # "label": null, # "api_version": "1.653.3" # } # } ``` -------------------------------- ### Retrieve Household Source: https://context7.com/policyengine/policyengine-api/llms.txt Fetches stored household input data by ID. ```APIDOC ## GET /{country_id}/household/{household_id} — Retrieve household ### Description Fetches stored household input data by ID. ### Method GET ### Endpoint /{country_id}/household/{household_id} ### Parameters #### Path Parameters - **country_id** (string) - Required - The identifier for the country (e.g., `us`, `uk`, `ca`, `ng`, `il`). - **household_id** (integer) - Required - The unique identifier for the household. ### Request Example ```bash curl https://api.policyengine.org/us/household/12345 ``` ### Response Example ```json { "status": "ok", "message": null, "result": { "id": 12345, "country_id": "us", "household_json": { ... }, "household_hash": "abc123", "label": null, "api_version": "1.653.3" } } ``` ``` -------------------------------- ### Create or retrieve a policy Source: https://context7.com/policyengine/policyengine-api/llms.txt Stores a policy reform as a JSON map of parameter paths to time-bounded overrides. Returns an existing policy ID if an identical policy exists, otherwise creates a new record. ```APIDOC ## POST /{country_id}/policy ### Description Stores a policy reform as a JSON map of parameter paths to time-bounded overrides. If an identical policy already exists the existing `policy_id` is returned with HTTP 200; otherwise a new record is created and HTTP 201 is returned. ### Method POST ### Endpoint `/{country_id}/policy` ### Request Body - **label** (string) - Required - A descriptive label for the policy. - **data** (object) - Required - A map of parameter paths to time-bounded overrides. ### Request Example ```json { "label": "Raise IRS exemption to $10k", "data": { "gov.irs.income.exemption.amount": { "2024-01-01.2030-12-31": 10000 } } } ``` ### Response #### Success Response (200 or 201) - **status** (string) - Indicates the success of the operation. - **message** (string) - A message indicating policy creation or retrieval. - **result** (object) - Contains the policy ID. - **policy_id** (integer) - The ID of the created or existing policy. ``` -------------------------------- ### Baseline and Reform Policy Comparison JSON Source: https://github.com/policyengine/policyengine-api/blob/master/tests/snapshots/simulation_analysis_prompt_region_enhanced_us.txt This JSON snippet represents a comparison between baseline and reform policies, indicating a specific parameter's value change. It's used to define the scope of policy changes for simulation. ```json {'gov.test.parameter': 0.1} ``` -------------------------------- ### Saved Policies Source: https://context7.com/policyengine/policyengine-api/llms.txt APIs for saving and retrieving user-specific policies. ```APIDOC ## `POST /{country_id}/user-policy` — Save a policy to a user's list ### Description Associates a reform/baseline policy pair with a user account for later retrieval. ### Method POST ### Endpoint `/{country_id}/user-policy` ### Request Body - **user_id** (integer) - Required - The ID of the user. - **reform_id** (integer) - Required - The ID of the reform policy. - **reform_label** (string) - Required - The label of the reform policy. - **baseline_id** (integer) - Required - The ID of the baseline policy. - **baseline_label** (string) - Required - The label of the baseline policy. - **year** (string) - Required - The year the policy applies to. - **geography** (string) - Required - The geography the policy applies to. - **number_of_provisions** (integer) - Required - The number of provisions in the policy. - **api_version** (string) - Required - The API version used. - **added_date** (string) - Required - The date the policy was added. - **updated_date** (string) - Required - The date the policy was last updated. - **budgetary_impact** (number) - Required - The budgetary impact of the policy. ### Request Example ```json { "user_id": 42, "reform_id": 67890, "reform_label": "Raise IRS exemption to $10k", "baseline_id": 2, "baseline_label": "Current law", "year": "2024", "geography": "us", "number_of_provisions": 1, "api_version": "1.653.3", "added_date": "2024-06-01", "updated_date": "2024-06-01", "budgetary_impact": -12500000000 } ``` ### Response #### Success Response (200) - **status** (string) - The status of the request. - **message** (string) - A message describing the result. - **result** (object) - The saved policy details. ## `GET /{country_id}/user-policy/{user_id}` — Get user's saved policies ### Description Returns all policy pairs saved by a given user. ### Method GET ### Endpoint `/{country_id}/user-policy/{user_id}` ### Response #### Success Response (200) - **status** (string) - The status of the request. - **message** (string | null) - A message describing the result. - **result** (array) - A list of saved policies. ``` -------------------------------- ### Update Household Data Source: https://context7.com/policyengine/policyengine-api/llms.txt Use this endpoint to replace all stored data for an existing household. Ensure the Content-Type is set to application/json and the request body contains the household data in JSON format. ```bash curl -s -X PUT https://api.policyengine.org/us/household/12345 \ -H "Content-Type: application/json" \ -d '{ "data": { "people": { "you": { "age": { "2024": 41 }, "employment_income": { "2024": 55000 } } }, "tax_units": { "your tax unit": { "members": ["you"] } }, "families": { "your family": { "members": ["you"] } }, "marital_units":{ "your marital unit":{ "members": ["you"] } }, "households": { "your household": { "members": ["you"], "state_name": { "2024": "CA" } } }, "spm_units": { "your household": { "members": ["you"] } } } }' ``` -------------------------------- ### Poverty Rates by Age Group JSON Source: https://github.com/policyengine/policyengine-api/blob/master/tests/snapshots/simulation_analysis_prompt_region_enhanced_us.txt This JSON presents baseline and reform poverty rates segmented by age group. It allows for an assessment of how the policy affects different age demographics concerning poverty. ```json {"baseline": 0.1, "reform": 0.2} ``` -------------------------------- ### Health Probes Source: https://context7.com/policyengine/policyengine-api/llms.txt Kubernetes/GCP App Engine health probe endpoints; both return plain-text OK with HTTP 200. ```APIDOC ## GET /liveness-check and GET /readiness-check — Health probes ### Description Kubernetes/GCP App Engine health probe endpoints; both return plain-text `OK` with HTTP 200. ### Method GET ### Endpoint /liveness-check /readiness-check ### Request Example ```bash curl https://api.policyengine.org/liveness-check ``` ### Response Example ``` OK ``` ``` -------------------------------- ### Search policies Source: https://context7.com/policyengine/policyengine-api/llms.txt Searches stored policies by a label substring and returns a list of policies matching the query. Requires the country ID. ```APIDOC ## GET /{country_id}/policies ### Description Searches stored policies by label substring and returns a list of `{ id, label }` objects. ### Method GET ### Endpoint `/{country_id}/policies` ### Query Parameters - **query** (string) - Required - The substring to search for in policy labels. - **unique_only** (boolean) - Optional - If true, returns only unique policy labels. ``` -------------------------------- ### Country Metadata Source: https://context7.com/policyengine/policyengine-api/llms.txt Returns all variables, parameters, entities, economy options, the current-law policy ID, and the country-package version for a given country. This is the primary discovery endpoint for building UI forms and knowing which variable names are valid. ```APIDOC ## GET /{country_id}/metadata — Country metadata ### Description Returns all variables, parameters, entities, economy options, the current-law policy ID, and the country-package version for a given country. This is the primary discovery endpoint for building UI forms and knowing which variable names are valid. ### Method GET ### Endpoint /{country_id}/metadata ### Parameters #### Path Parameters - **country_id** (string) - Required - The identifier for the country (e.g., `us`, `uk`, `ca`, `ng`, `il`). ### Request Example ```bash # Retrieve US metadata curl https://api.policyengine.org/us/metadata | python3 -c " import sys, json data = json.load(sys.stdin) result = data['result'] print('Country package version:', result['version']) print('Current law policy ID:', result['current_law_id']) print('Sample variables:', list(result['variables'].keys())[:5]) print('Sample parameters:', list(result['parameters'].keys())[:3]) " ``` ### Response Example ```json { "result": { "version": "1.653.3", "current_law_id": 2, "variables": { "employment_income": { ... }, ... }, "parameters": { "gov": { ... }, ... }, "entities": { ... }, "economy_options": { ... } } } ``` ```