A request is more than a URL. It has a method, a set of parameters, and a
timeout, and the service on the other side reads each part. This lesson looks
at the two pieces you build yourself: the query parameters, and the timeout.
HttpRequest holds what you want to happen. setEndpoint sets the address,
setMethod sets the verb (GET to read, POST to create), and setTimeout
sets how long the platform waits before it gives up.
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://dummyjson.com/products/search?q=phone');
request.setMethod('GET');
request.setTimeout(30000);
HttpResponse response = http.send(request);
Always set a timeout. Without one the platform uses a short default, and a slow
service fails the request rather than the whole transaction.
The part of the address after the ? is the query string. It holds named
values: a name, an =, and the value. ?q=phone asks the product search for
the products that match the word phone. When the service takes more than one
value, separate them with an &:
request.setEndpoint('https://dummyjson.com/products/search?q=phone&limit=10');
A value in a URL cannot hold a space, and the reserved characters & and =
mean something to the service. EncodingUtil.urlEncode turns a value into the
form the URL can carry: a space becomes +, and & becomes %26.
String encoded = EncodingUtil.urlEncode(searchTerm, 'UTF-8');
request.setEndpoint('https://dummyjson.com/products/search?q=' + encoded);
Send the search term raw and the service answers with an error status and an
empty body. Nothing about the response tells you which word went wrong, so
encode every value you put in a query string.
The search endpoint answers with a JSON object that holds four keys: total,
limit, skip, and products. total is how many products matched the
search. products holds only the rows of the current page, 30 of them by
default, so a search that matches 41 products sends back 41 in total and 30
rows in products. Read total when you want the number of matches, and add
a limit parameter when you want fewer rows.
A value with a raw space in it is the most common mistake, and the response is
an error with an empty body. The second is reading the size of the products
array instead of total, which gives you the size of one page rather than the
number of matches. The third is a misspelled parameter name: the service
ignores a name it does not know, so the search returns the whole catalogue
instead of the matches you asked for. A blank search term does the same thing,
because an empty query matches everything.