Skip to main content

Create an API

Lesson Objectives

  1. Define API
  2. Create Holiday
  3. Setup JSON Server
  4. Checking the REST routes

Define API

  • An API stands for Application Program Interface
  • It is a set of routines, protocols, and tools for building software applications
  • It specifies how software components should interact
  • Essentially it's documentation, but in the industry, it's come to mean a program or some existing software that you use to build your own app
  • Now we will use JSON Server to make our own and have React consume it

What we're building

We live in a time where there are so many holidays! Many times we forget to celebrate. So we'll build a holidays app to create, show and delete our holidays, we'll also be able to update whether or not we've celebrated the holiday

First we'll build our API which will just serve JSON. We'll create, update, and delete using cURL

Once we have built and tested our back end we'll build our React front end

Class build:

holidays app example

For lab, you'll continue on your own to click the balloons in order to increase likes and press the pencil to show a pre-filled form to let you edit the whole field:

holidays app lab portion

Set Up

In student examples for today:

  1. npm create vite
    • ✔ Project name: … holidays
    • ✔ Select a framework: › React
    • ✔ Select a variant: › JavaScript + SWC
  2. cd holidays
  3. npm install
  4. Clean up unused portions of React

Create Holidays

  1. touch db.json

Our holidays should:

  • have a required name
  • a boolean of whether or not it is a public holiday
  • a description, let's default it to best holiday ever!
  • likes, a number, default it to 0
db.json
{
"holidays": [
{
"name": "New Year Day",
"celebrated": true,
"description": "Start of year",
"likes": 0,
"id": 1
},
{
"name": "Good Friday",
"celebrated": true,
"description": "Commemorates the crucifixion of Jesus and his death at Calvary",
"likes": 0,
"id": 2
},
{
"name": "Labour Day",
"celebrated": true,
"description": "Celebrates the achievements of workers",
"likes": 0,
"id": 3
},
{
"name": "Hari Raya Puasa",
"celebrated": true,
"description": "Marks the end of the month-long dawn-to-sunset fasting of Ramadan",
"likes": 0,
"id": 4
},
{
"name": "Vesak Day",
"celebrated": true,
"description": "Most important Buddhist festival",
"likes": 0,
"id": 5
},
{
"name": "Hari Raya Haji",
"celebrated": true,
"description": "Honours the willingness of Abraham to sacrifice his son Ishmael as an act of obedience to God's command",
"likes": 0,
"id": 6
},
{
"name": "Chinese New Year",
"celebrated": true,
"description": "New Year in the Chinese lunar calendar",
"likes": 0,
"id": 7
},
{
"name": "Mother's Day",
"celebrated": false,
"description": "Celebrate mothers",
"likes": 0,
"id": 8
},
{
"name": "Father's Day",
"celebrated": false,
"description": "Celebrate fathers",
"likes": 0,
"id": 9
},
{
"name": "Children's Day",
"celebrated": false,
"description": "Celebrate children",
"likes": 0,
"id": 10
}
]
}

Setup JSON Server

We need to setup the right URL routes:

  1. touch routes.json
routes.json
{
"/api/*": "/$1"
}

Next we install json-server to work as a API server and database for us.

  1. npm install json-server

We need to add a new script in package.json

package.json
{
"scripts": {
"db": "npx json-server --watch db.json --routes routes.json"
}
}
info

Remember you run the above in another Terminal with the npm run db command

URI Patterns

We want to build maintainable, scalable applications.

To do that, we want to have a plan on how we name our URLs.

Let's say we want to make an app that tracks bookmarks for us.

We want to be able to

  • Create a bookmark
  • See a list of our bookmarks
  • See the details of one bookmark
  • Update a bookmark
  • Delete a bookmark

Let's take ~5 minutes to answer: How should we organize our URLs?

Good URIs shouldn't change

When you provide a link, it should always work.

resource

Some URI Pain points

  • version 2.0, reorganization to make the app better (while the app should improve, the URIs should be able to stay constant, if they were designed well)
  • confidential/valid/up to date/out of date - how to organize?
  • moving files - you should be able to move files without changing the URI
  • making the name too specific/have too many details ie putting /jane in the URL because she worked on it. Then John takes over part of Jane's work. Yikes.

Describe REST and list the various routes

Lucky for us, some brilliant minds have developed a URI pattern that solves a lot of the above problems. If we follow the pattern, we can alleviate a lot of pain points.

  • REST stands for Representational state transfer
  • It's just a set of principles that describe how networked resources are accessed and manipulated
  • We have 6 RESTful routes that allow us basic operations for reading and manipulating a collection of data:

Using Insomnia or Postman, we can check the following routes (where :id is some number like 3):

ActionURLHTTP VerbRequest Body
Index/api/holidays/GETNo
Show/api/holidays/:idGETNo
Create/api/holidays/POSTYes
Update(Replace)/api/holidays/:idPUTYes
Update(Patch)/api/holidays/:idPATCHYes
Destroy/api/holidays/:idDELETENo

Alternatively we can use cURL to check out the routes

Describe what is cURL

Describe when we might use cURL

  • You want to create a route and test that it works
    • with a GET request, you can just type the route into the URL bar in the browser and see if it works. No muss no fuss
    • Separate the functionality of React from your routes so you build more iteratively and you can isolate bugs better
  • In order to test routes like POST:
    • you can't just make the request in the browser by entering the path in the URL bar like you would with a GET request
      • the only way to test a POST request in the browser is via forms
      • if you have to create a form first there is a lot more code to write, before you can test it:
        1. create a /new route
        2. create a file with forms
        3. have the forms point to the correct POST route
        4. go to the /new route in the browser
        5. fill out the form
        6. click submit
  • With cURL, we can make a POST request directly to the server without needing to go through all the set up

Use cURL to test a GET request

Within the terminal execute the following:

curl https://generalassemb.ly

Neat! To try it for our app above use:

  • curl http://localhost:3000/api/holidays/
  • curl http://localhost:3000/api/holidays/3

Use cURL to test a POST request

test: curl -X POST -H "Content-Type: application/json" -d '{"name":"My new holiday"}' http://localhost:3000/api/holidays/

Use cURL to test a PATCH request

test: curl -X PUT -H "Content-Type: application/json" -d '{"name":"I updated this"}' http://localhost:3000/api/holidays/3

Use cURL to test a PUT request

test: curl -X PATCH -H "Content-Type: application/json" -d '{"name":"I updated this"}' http://localhost:3000/api/holidays/3

Use cURL to test a DELETE request

test: curl -X DELETE localhost:3000/api/holidays/1