DEV Community

Cover image for Simple REST API Tutorial For Beginners
Helitha Rupasinghe
Helitha Rupasinghe

Posted on • Updated on

Simple REST API Tutorial For Beginners

What is REST (Representational State Transfer)?

When a RESTful API is called, the server will transfer to the client a representation of the state of the requested resource.

The representation of the state can be in a JSON format, and probably for most APIs this is indeed the case. (It can also be in XML or HTML format)

What does the server do?

When you, the client, call one of its APIs depends on 2 things that you need to provide to the server:

  • An identifier for the resource you are interested in. This is the URL for the resource, also known as the endpoint. In fact, URL stands for Uniform Resource Locator.
  • The operation you want the server to perform on that resource, in the form of an HTTP method, or verb. The common HTTP methods are GET, POST, PUT, and DELETE.

How does it work?

REST APIs communicate via HTTP requests to perform standard database functions like creating, reading, updating, and deleting records (also known as CRUD) within a resource. For example...

  • A REST API would use a GET request to retrieve a record,
  • A POST request to create one,
  • A PUT request to update a record,
  • And a DELETE request to delete one.

All HTTP methods can be used in API calls. A well-designed REST API is similar to a website running in a web browser with built-in HTTP functionality.

Project Setup

  1. Run this code in your command prompt to create a new react app.
npx create-react-app rest-api
Enter fullscreen mode Exit fullscreen mode

1a. CD into the app folder

cd rest-api
Enter fullscreen mode Exit fullscreen mode

1b. Run npm start

Now your project is up and running. Let's start coding!

ReactRunning.png

Folder Structure

On the root level, we will keep the following files.

  • Index.JS
  • App.JS
  • App.CSS
  • Index.CSS

App Component

Clean up your App.js by removing everything within the div and get it to look like this.

import React from 'react';
import './App.css';

function App(){
  return (
    <div className="App">
    Hello World!
    </div>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

Fetching API Data

Now let's log the data from the QuotesApi using useEffect Hook.

import './App.css';
import React,{useEffect} from 'react';

export default function App() {

  useEffect(() => {

  }, []);


  return (
    <div className="App">

    </div>
  );

}

Enter fullscreen mode Exit fullscreen mode

Define Your URL

  useEffect(() => {
    const url = "https://type.fit/api/quotes";

  }, []);
Enter fullscreen mode Exit fullscreen mode

Create the asynchronous function

Then create an asynchronous function to fetch our data. For this usecase the function will need to wait after the data is fetched (our promise) before continuing.

  const fetchData = async () => {
      try {
          const res = await fetch(url);
          const json = await res.json();
          console.log(json);
      } catch (err) {
          console.log("error", err);
      }
  };
Enter fullscreen mode Exit fullscreen mode

Put the fetchData function within the useEffect hook and remember to call it like so.

  useEffect(() => {
    const url = "https://type.fit/api/quotes";

    const fetchData = async () => {
      try {
          const res = await fetch(url);
          const json = await res.json();
          console.log(json);
      } catch (err) {
          console.log("error", err);
      }
  };

  fetchData();
  }, []);
Enter fullscreen mode Exit fullscreen mode

The function just created is wrapped within a try...catch statement to catch the errors and prints them in the console. Why do we do this? To help debug and prevent the app from crashing unexpectedly.

Check your console.log statement and see if your getting the correct data from the API like so.

Consolelog.png

How do we grab the data from the api?

To do that we will have to import useState from react and define it.

import React,{useEffect, useState} from 'react';
Enter fullscreen mode Exit fullscreen mode
 setQuotes(json);
Enter fullscreen mode Exit fullscreen mode

And then your return body should look like so:

  return (
    <table className="App">
    <tr>
        <th>Text</th>
        <th>Author</th>
    </tr>
    {quotes.map(({ author, text }, index) => (
        <tr key={index}>
            <th>{text}</th>
            <th>{author}</th>
        </tr>
    ))}
    </table>
  );
Enter fullscreen mode Exit fullscreen mode

Now let's put everything together along with any styling to complete the project!

import './App.css';
import React,{useEffect, useState} from 'react';

export default function App() {

  const [quotes, setQuotes] = useState([]);

  useEffect(() => {
    const url = "https://type.fit/api/quotes";

    const fetchData = async () => {
      try {
          const res = await fetch(url);
          const json = await res.json();
          console.log(json);
          setQuotes(json);
      } catch (err) {
          console.log("error", err);
      }
  };

  fetchData();
  }, []);


  return (
    <table className="App">
    <tr>
        <th>Text</th>
        <th>Author</th>
    </tr>
    {quotes.map(({ author, text }, index) => (
        <tr key={index}>
            <th>{text}</th>
            <th>{author}</th>
        </tr>
    ))}
    </table>
  );
}

Enter fullscreen mode Exit fullscreen mode

Check the console again and view the data your getting from the API.

This will be the Output.

Result

Looks Amazing!

Thank you so much for making it to the end, have a great day!

Top comments (2)

Collapse
 
hr21don profile image
Helitha Rupasinghe

Thanks for your comment.

I look forward to making these changes!

Collapse
 
hr21don profile image
Helitha Rupasinghe • Edited

Alternatively, you can fork this random quotes machine.

Codepen - codepen.io/hr21don/full/KKyPQKO

Netlify - dazzling-souffle-ae8422.netlify.app/