Home > OS >  How would I generate API call via Python while reading data from csv flle? I am using Pandas library
How would I generate API call via Python while reading data from csv flle? I am using Pandas library

Time:07-12

I am still learning Data Engeineering and Data Science, new and appreciate any advice.

Long story short, I have managed to create Pandas script which updates already existing csv file into another one I need for further actions. Data sorted out, I lave learned so many things there. Good job. Script:

import pandas as pd
dataset = "csv_file.csv"
df = pd.read_csv(dataset, usecols=[0,1], header=0, names=['title', 'product_id'])
df['title'] = df['title'].str.replace('"', "''")
df['title'] = '"'   df['title']   '"'
print(df.head())
df.to_csv(f'edited_csv.csv')

Now, I have been thinking about automation for running some bulk tasks I have. So, I am working on a small script so I can make numerous API calls where I am creating the product, using the title and product_id from the edited csv file.

I was googling for a few days and found some sources. Until I get approval for testing, I would like to check this one out, to see if I am on the right path, or I should change the way I am thinking and learn some new ways.

The edited csv file looks something like this:

title, product_id
"Name 1", 12345
"Name 2", 98765
"Name 3", 34566
"Nime 4", 78930
"Name 5", 99850

So, I have been implementing another small script for making those API calls. I hope I somehow got the point, but may miss a few things:

api_token = "my_token"
df = pd.read_csv('edited_csv.csv')

    for i in range(len(df)):
        
        endpoint = f"/api/mystore/products"
        request_body = {
            "product_id": df['product_id'],
            "title": df['title'],
            "my_discount_type": "percentage",
            "my_discount_amount": 15,
            "store": "Store3",
            "versions": "Black/White/Red"
        }
        }

So, the goal would be to make products one by one, line by line, until I reach the end. I was a bit in dilemma if I should use while loop.

Thank you in advance, good people.

CodePudding user response:

I think the code works fine except that you have called entire columns of dataframe in the for loop. I think if you modify it to the following you should be fine.

api_token = "my_token"
df = pd.read_csv('edited_csv.csv')

for i in range(len(df)):
    
    endpoint = f"/api/mystore/products"
    request_body = {
        "product_id": df['product_id'][i],
        "title": df['title'][i],
        "my_discount_type": "percentage",
        "my_discount_amount": 15,
        "store": "Store3",
        "versions": "Black/White/Red"
    }
    # call the api and do the rest of stuff you want to do.
    }
  • Related