CodeBlanks Logo Icon CodeBlanks

GET request

Learn to make GET requests with fetch.

What is a GET request?

GET is the HTTP method used to read a resource from the server. fetch's default method is GET; so when you write fetch(url) it automatically makes a GET request. To be explicit you can write fetch(url, { method: "GET" }).

A GET request fetches data from the server; it does not change anything on the server. So it fits listing, searching, viewing a profile. To create data you use POST, to delete you use DELETE, to update you use PUT. GET request parameters are appended to the URL: ?userId=1 for example. These parameters are called a query string. GET requests can be cached by the browser; so they fit data that does not change often.

URL and query string

In a GET request parameters are appended to the URL. These parameters are called a query string; it starts with ? and items are separated by &. Example: https://api.example.com/users?role=admin&active=true.

The query string gives the server filtering or search information. The server looks at these parameters and returns the right data. The URL length has an upper limit in browsers and servers; so sending very long data through a query string is not a good fit. For large data use POST. Special characters in the URL (space, Turkish letters) must be encoded with encodeURIComponent. This turns a space into a safe string like %20. fetch's URL must be properly encoded; otherwise the request can fail.

Practice Fetch a user with GET

Write a ProfileLoader component. Assign fetch("https://api.example.com/users/1") to a const promise. Add a promise.then(response => console.log(response.status)) call. The component returns null.

Starter code

App.js
// Call fetch

function ProfileLoader() {
  // Make a GET request to user 1 with fetch
  // Log the response status code with promise.then

  return null;
}

Sample solution

App.js
function ProfileLoader() {
  const promise = fetch("https://api.example.com/users/1");
  promise.then(response => console.log(response.status));
  return null;
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Write the GET method explicitly

Question
fetch(url, { method: "____" });
Answer
fetch(url, { method: "GET" });

Explanation: The GET method reads data from the server.

2 Match the concept to its role

Term Meaning
GET Reads data
POST Adds new data
query string URL parameters
URL Request address

3 What is fetch's default HTTP method?

App.js
fetch("https://api.example.com/users");
  • DELETE
  • GET Correct answer
  • POST
  • PUT

Explanation: fetch's default method is GET.

All lessons in Intermediate