0

So I'm trying to learn python so I can work with an api. The tutorial I was using was using python 2 and urllib. I'm running python 3.6, so it wasn't working. So I decided to try and learn about requests. I'm having a little bit of trouble converting from urllib to requests.

import requests import json parameters = {"apikey": "mykey", "queries": "SN74S74N"} response = requests.get("http://octopart.com/api/v3/parts/match", params = parameters) data = response.json() #print(type(data)) print(data) 

The error I get when I run this is

{'message': 'JSON decode error: SN74S74N', '__class__': 'ClientErrorResponse'} 

I'm not sure why I'm getting this error. But I think it might be because my parameters aren't set up right. Is requests capable of doing the same thing they have in the documentation? https://octopart.com/api/docs/v3/rest-api#endpoints-parts-match

Sorry this is vague, I just started learning python and apis. Will be around to further clarify any questions.

4
  • According to the documentation octopart.com/api/docs/v3/rest-api#endpoints-parts-match, the value of queries= shouldn't be a simple string like SN74S74N. Commented Dec 20, 2017 at 18:33
  • So a quick look at the octopart API docs make it look like this is an error their API is returning saying your queries value isn't in the format they expect. Requests is doing what it should, but you'll need to work on formatting the query. Commented Dec 20, 2017 at 18:33
  • The documentation (octopart.com/api/docs/v3/overview) seems to indicate the "queries" parameter should be a list of dictionaries, not a string. Like in their Python example: `queries = [ {'mpn': 'SN74S74N', 'reference': 'line1'}, {'sku': '67K1122', 'reference': 'line2'}, {'mpn_or_sku': 'SN74S74N', 'reference': 'line3'}, {'brand': 'Texas Instruments', 'mpn': 'SN74S74N', 'reference': 'line4'} ]´ Commented Dec 20, 2017 at 18:35
  • 1
    Basically, follow their tutorial as far as building the queries list of dicts, serialize it into json, then pass that in as part of your dict - parameters = {"apikey": "mykey", "queries": json.dumps(queries)}. requests handles the URI escaping but you still need to give it json. Commented Dec 20, 2017 at 18:35

1 Answer 1

1

From looking at the docs you provided for the API it looks like your parameters aren't structured how the API requires it.

Under the examples section, it shows the queries sent with the request as:

queries = [ {'mpn': 'SN74S74N', 'reference': 'line1'}, {'sku': '67K1122', 'reference': 'line2'} ] 

So for your example you need:

queries = [ {'mpn': 'SN74S74N', 'reference': reference goes here} ] 

and use the request as you have in your code.

link to the docs

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.