daxu
daxu

Reputation: 4074

pass a json object in query string for a web api?

I have a web API method, which takes json request object

{
    "FundCodes":["0DFOY"],
    "FromDate":"2021-04-01",
    "ToDate":"2021-05-01"
}

As this api retrieves data, I think the web API needs to be a GET.

However, if I do that, how do I pass above in a query string?

I know that HTTP GET does have a body and I can put the parameter in, but I think lots of people are against the idea of using a body. So how do I put this into query string?

I used this site to urlencode the parameter, but seems my API call doesn't recognise the passed parameter. https://onlinejsontools.com/url-encode-json

So is there a bit more official way on web API design for this? Maybe I should use POST other than GET?

Upvotes: 0

Views: 8120

Answers (1)

Rena
Rena

Reputation: 36655

The first way, you can pass query string like below:https://localhost:portNumber/WeatherForecast?fundcodes=aaa&fundcodes=bbb&fromDate=2021-04-01&toDate=2021-05-01.

Model:

public class TestModel
{
    public string[] FundCodes { get; set; }
    public string FromDate { get; set; }
    public string ToDate { get; set; }
}

Controller:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet]

    public IActionResult Get([FromQuery]TestModel model)
    {
        return Ok(model);
    }
}

The result you will get:

enter image description here

The second way, you can pass query string in browser like below:https://localhost:portNumber/WeatherForecast?json={"FundCodes":["0DFOY"],"FromDate":"2021-04-01","ToDate":"2021-05-01"}. The browser will dynamic encode this url and pass to backend.

If you want to send encoded url manually, the url should be: https://localhost:portNumber/WeatherForecast?json={%22FundCodes%22:[%220DFOY%22],%22FromDate%22:%222021-04-01%22,%22ToDate%22:%222021-05-01%22} or https://localhost:portNumber/WeatherForecast?json=%7B%22FundCodes%22%3A%5B%220DFOY%22%5D%2C%22FromDate%22%3A%222021-04-01%22%2C%22ToDate%22%3A%222021-05-01%22%7D.

Controller:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet]
    public IActionResult Get([FromQuery]string json)
    {
        var model = System.Text.Json.JsonSerializer.Deserialize<TestModel>(json);      
        return Ok(model);
    }
}

Upvotes: 3

Related Questions