Passing Data to ConvertCSV API

Passing Data to ConvertCSV API

All our conversion APIs require the "infile" parameter to identify the data to be converted. You may use the GET request if your data source is a URL or you have a small input string. If you are uploading a file, then we require a HTTP POST request. For POST, set enctype="multipart/form-data" if using HTML forms with a file upload, otherwise use "application/x-www-form-urlencoded".

Using CURL

When using the command line tool curl, there are 3 different ways to pass data to our API:
  1. POSTed form field:
    curl -X POST "https://www.convertcsv.io/api/v1/csv2json" -H "Authorization: Token XXXXX" ... -F "infile=@myfile.csv"
  2. GET for URL containing the data:
    curl "https://www.convertcsv.io/api/v1/csv2json?auth_token=XXXXX&infile="https%3A%2F%2Fjsonplaceholder.typicode.com%2Fusers"
    Note that the infile URL string must be URL encoded. See URL Encoder
  3. GET for less than 1K of data:
    curl "https://www.convertcsv.io/api/v1/csv2json?auth_token=XXXXX&infile="raw input data goes here, such as a CSV or JSON string"
    Note that the infile data must be URL encoded. If you are using an HTML form with the GET method, then this will be done for you. You may use this URL Encoder to URL data.
Each converter has optional parameters that should be passed as part of the query string of the URL, example: curl "https://www.convertcsv.io/api/v1/json2csv?auth_token=XXXXX&outtab=Y&infile=https%3A%2F%2Fjsonplaceholder.typicode.com%2Fusers"

Using Python

Here is an example of calling CSV to JSON using Python:
# Example API call to convertcsv.io CSV to JSON
import os
import requests

# URL and API token
token = os.environ.get("CONVERTCSV_TOKEN") 
input_filename = "example.csv"
output_filename = "MYOUTPUTFILE.EXT"
if token is None:
    raise ValueError("CONVERTCSV_TOKEN environment variable is not set.")

url = "https://www.convertcsv.io/api/v1/csv2json?"
headers = {
    "Authorization": f"Token {token}"
}

# Define the fields parameter
fields_param = "2,3,4"

# File to upload
files = {"infile": (input_filename, open(input_filename, "r"))}

# Make the POST request
response = requests.post(url, headers=headers, data={"fields": fields_param}, files=files, stream=True)

# Check if the request was successful (status code 200)
if response.status_code == 200:
    # Save the response content to a file
    with open(output_filename, "wb") as output_file:
        for chunk in response.iter_content(chunk_size=1024):
            if chunk:
                output_file.write(chunk)
        print(f"File downloaded successfully as {output_filename}")
else:
    print(f"Request failed with status code {response.status_code}")

Conclusion

This guide provides essential information for using ConvertCSV APIs effectively. Remember to URL encode your data and choose the appropriate method for your data's size and format.

Latest Tutorials