TypeError while following a tutorial

Viewed 35

I am facing a problem trying to fetch API data and convert to CSV

I have successfully printed data, but when I add the lines of code to sort the data, I get this error

     for x in myjson['data']:
TypeError: list indices must be integers or slices, not str

Here is my full line of code.

from ast import In
from email.mime import application
from webbrowser import get
import requests
import csv

from requests.api import head

url = "https://api-devnet.magiceden.dev/v2/collections/runecible/activities?offset=0&limit=100"

headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
}
response = requests.request("GET", url,headers=headers,data={})
myjson = response.json()
ourdata =[]

for x in myjson['data']:
    listing = [['collection'], ['price']]
    ourdata.append(listing)

print(ourdata)
1 Answers

The main problem is typo in url.

It has to be runcible instead of runecible (without e in run-e-cible)

See url in example in documentation:

https://api.magiceden.dev/#3a6c0dd2-067f-4686-9a8b-8994667f1b67

Other problem is that server sends data with different structure. It is NOT dictionary with ['data'] but it is list with many dictionares - and this need different code in for-loop.


Minimal working code.

I removed many elements because they are not needed.

import requests
import csv

url = "https://api-devnet.magiceden.dev/v2/collections/runcible/activities?offset=0&limit=100"

response = requests.get(url)

data = response.json()
print(data)

# --- 

ourdata = []

for item in data:
    ourdata.append( [item['collection'], item['price']] )

print(ourdata)

# ---

with open('output.csv', 'w', newline='') as fh:   # some systems may need `newline=''` to write it correctly
    writer = csv.writer(fh)  
    writer.writerow(['collection', 'price']) # `writerow` without `s` to write one row (with headers)
    writer.writerows(ourdata)                # `writerows` with `s` to write many rows (with data)

BTW:

You can also run it as

url = "https://api-devnet.magiceden.dev/v2/collections/runcible/activities"

payload = {
    "offset": 0,
    "limit": 100,
}    

response = requests.get(url, params=payload)

EDIT:

To make sure (because in similar question this also made problem):

Url api-devnet. (Devnet) is for testing and it may have fake or outdated values.
If you will need real data then you will need to use url api-mainnet. (Mainnet).

Text from documentation:

Devnet: api-devnet.magiceden.dev/v2 - this uses a testing Solana cluster, the tokens are not real
Mainnet: api-mainnet.magiceden.dev/v2 - this uses the real Solana cluster, the tokens are real and this is consistent with the data seen on https://magiceden.io/

BTW: In documentation at the top you can select language - ie. Python Requests - and it will show all examples in this language. But some code can be reduced.

Related