简体   繁体   中英

Metrc Python rest api

I am trying to use python to make http requests. I seem to be having some trouble. If anyone has some ideas on how to fix this, that would be awesome!

Documentation: Both API keys are combined into a single string in the following manner:

software_api_key:user_api_key

software_api_key = Software vendor's API key

user_api_key = User's API key

The combined string is then encoded using RFC2045-MIME Base64 without the 76 char/line limit. The HTTP header value is composed of the literal word Basic followed by a space and the encoded string: Basic encoded_api_keys

Python (please note i removed the actual vendor and user api key as they are not suppose to be public)

import requests
import json

url = 'https://sandbox-api-ca.metrc.com/packages/v1/create?licenseNumber=CAL17-0000005'

with open('cal.json') as json_file:
json_data = json.load(json_file)

headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
cred = ('api key', 'User Key')

response = requests.post(url, headers=headers, json=json_data, auth=cred)
print(response.text)
print(response)

error code 400 Bad Request

Now the bad request signifies my json file may be wrong but i have copied and pasted from their own documentation.

I know this question is old, but this might help someone having the same issue.

import base64

from SECRETS import MetrcKeys


def get_metrc_encoding():
    vendor_key = MetrcKeys.vendor_key # Your vendor key
    user_key = MetrcKeys.user_key # Your user key
    encoding_str = f"{vendor_key}:{user_key}"
    encoding = base64.b64encode(encoding_str.encode())
    encoding = encoding.decode('ASCII')
    return encoding


def get_metrc_header():
    return {
        'Authorization': f"Basic {get_metrc_encoding()}"
    }

Your request would look like:

response = requests.post(url, headers=get_metrc_header(), json=json_data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM