1

I'm writing an API and would like people to be able to supply a Google Charts API call as an argument. What's the proper way to deconstruct this problematic API call, where an argument contains an entirely separate API call?

For instance:

?method=createimage&chart1=https://chart.googleapis.com/chart?chs=250x100&chd=t:60,40&cht=p3&chl=Hello|World

In the example above, I'd like to think of it as (2) query string keys: method and chart1. Is it possible for me to parse the above example as 2 query string keys, leaving the Google Charts API call intact, rather than breaking it down? Could I enclose the call as JSON or something along those lines?

Thanks much! Cheers

Hairgami_Master
  • 5,429
  • 10
  • 45
  • 66

2 Answers2

6

Here's the proper way (using the ParseQueryString method):

using System;
using System.Web;

class Program
{
    static void Main()
    {
        var query = "?method=createimage&chart1=https://chart.googleapis.com/chart?chs=250x100&chd=t:60,40&cht=p3&chl=Hello|World";
        var values = HttpUtility.ParseQueryString(query);
        Console.WriteLine(values["method"]);
        Console.WriteLine(values["chart1"]);
    }
}

and if you wanted to construct this query string:

using System;
using System.Web;

class Program
{
    static void Main()
    {
        var values = HttpUtility.ParseQueryString(string.Empty);
        values["method"] = "createimage";
        values["chart1"] = "https://chart.googleapis.com/chart?chs=250x100&chd=t:60,40&cht=p3&chl=Hello|World";
        Console.WriteLine(values);
        // prints "method=createimage&chart1=https%3a%2f%2fchart.googleapis.com%2fchart%3fchs%3d250x100%26chd%3dt%3a60%2c40%26cht%3dp3%26chl%3dHello%7cWorld"
    }
}

Oh and by the way, what you have shown in your question is an invalid query string which is confirmed by the output of the second code snippet I have shown. You should URL encode your chart1 parameter. It's absolutely against all standards to have more than one ? character in a query string.

Here's how the correct query string would look like:

?method=createimage&chart1=https%3A%2F%2Fchart.googleapis.com%2Fchart%3Fchs%3D250x100%26chd%3Dt%3A60%2C40%26cht%3Dp3%26chl%3DHello%7CWorld
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Ha! Thanks. I assumed it would be more difficult than that. I should have tried it first. Thanks so much for your help! Much appreciation. – Hairgami_Master Jan 26 '12 at 22:56
0

You should URL encode the URL in your query string, as it contains reserved characters. Alternatively, hex encoding works just fine too.

Once you have done so, you can treat the two values separately and parsing is simple.

Community
  • 1
  • 1
Tim M.
  • 53,671
  • 14
  • 120
  • 163