Retrieve data from a query with required variables with python

I wrote this code to extract data from a query I wrote and it requires 2 variables: start_date, end_date.

This is the code I wrote:

import os
import json
import pandas as pd
import requests
from io import StringIO

def ret_metabase(question, p1_start_date=None, p1_end_date=None):
    question_id = str(question)
    file_name = 'meta_results.csv'
    # Do not modify below this
    base_url = ''
    base_headers = {'Content-Type' : 'application/json'}
    os.environ['METABASE_USER_NAME'] = 'my user'
    os.environ['METABASE_PASSWORD'] = 'my pass'

        s_response = + '/session', 
                                data = json.dumps({'username': os.environ["METABASE_USER_NAME"], 'password': os.environ["METABASE_PASSWORD"]}), 

        session_token = s_response.json()['id']                        
        base_headers['X-Metabase-Session'] = session_token

        # Modify request data to include parameter values if they are provided
        if p1_start_date and p1_end_date:
            data = {
                "parameters": [
                        "type": "date",
                        "value": p1_start_date,
                        "target": [
                            ["template-tag", "start_date"]
                        "type": "date",
                        "value": p1_end_date,
                        "target": [
                            ["template-tag", "end_date"]
            p_response = + '/card/' + question_id + '/query/csv', headers=base_headers, data=json.dumps(data))
            p_response = + '/card/' + question_id + '/query/csv', headers=base_headers)

        my_dict = p_response.content
        s = str(my_dict,'utf-8')
        my_dict = StringIO(s) 
        df = pd.read_csv(my_dict)

    except requests.exceptions.HTTPError as errh:
    except requests.exceptions.ConnectionError as errc:
    except requests.exceptions.Timeout as errt:
    except requests.exceptions.RequestException as err:

v = ret_metabase(18182)

This code works perfectly fine with queries that does not have any variables required, it returns nothing when I give it an id with required parameters.
Your help is very much appreciated.
Note: I pass the start_date and end_date in this format: v = ret_metabase(18182, '2023-02-01', '2023-02-02')

Because you're specifying a format ( e.g. /query/csv), you need to put the parameters in the url, like this:

data = [ { "type": "date", "value": p1_start_date, "target": [ "variable", ["template-tag", "start_date"] ] }, { "type": "date", "value": p1_end_date, "target": [ "variable", ["template-tag", "end_date"] ] } ]

url = url + '?parameters=' + json.dumps(data2)

res =, headers=headers, params=params)