0

I have two APIs which requires two different query string/param structure, I have been trying to figure it out myself how to do this but I'm not getting anywhere.

Both APIs are GET request however API 1 URL request is something like

www.website.com/api/User?username=niceguy

API 2 request URL, because this doesn't have an input its basically just a click of a button to do its search, whereas the API 1 does have an input to build its query string structure.

www.website.com/api/User

Two different query strings but returns the same objects, I'm only using 1 search function for dynamic purpose therefore I'm finding it hard to construct my query string.

I created a function to build the query string however it only takes the API 1 structure.

Can someone point out how the HTTP request can also take API 2 structure?

function queryStringBuild() {
 let result: string = "?";
        //for each of the input search terms...
   this.searchBoxCount.forEach((inputSearch: any) => {
     // first reparse the input values to individual key value pairs
     // Checks which field is not null and with empty string (space)
     if (inputSearch.value != null && (inputSearch.value != "")) {
        let inputValues: string = inputSearch.value
             .split("\n")
             .filter(function (str) { return str !== "" })
             .join("&" + inputSearch.name + "=");
             // then add it to the overall query string for all searches
             result = result + inputSearch.name + "=" + inputValues + "&"
       }
   });
   // remove trailing '&'
   result = result.slice(0, result.length - 1);
   return result;
}

API request

getRequest() {
 this.http.get('www.website.com/api/' + this.queryStringBuild)
 ...
}
MrNew
  • 1,384
  • 4
  • 21
  • 43

1 Answers1

0

I'd propose a different solution by using URLSearchParams.

let params = new URLSearchParams();
this.searchBoxCount.forEach((inputSearch: any) => {
    if (inputSearch.value != null && (inputSearch.value != "")) {
        let filteredValue = inputSearch.split("\n")
                                       .filter(x => x != "")
                                       .join(",");

        params.set(inputSearch.name, filteredValue);
    }
}

this.http.get('www.website.com/api', { search: params });

I don't know exactly how your API works, so how multiple values for the same parameter get concatenated is up to you.

See this post for more information

Community
  • 1
  • 1
Maximilian Riegler
  • 22,720
  • 4
  • 62
  • 71