Skip to content

LAB3_Expose your "hello world" API

David Jones-Gilardi edited this page Feb 22, 2021 · 11 revisions

βš’οΈ Expose your "hello world" API

Objectives

The REST API is stateless, and therefore helps functions scale horizontally. Here we will:

  • Create test cases to check that our API call is working correctly
  • Build the API call to Astra to create a game document, based on the requirements from our test

What we will cover:

  1. Setup your environment
  2. Make a serverless endpoint using Netlify functions
  3. Merge back to master
  4. Check your deployment in Netlify

1. Setup your environment

βœ… Step 1a: Launch IDE

IMPORTANT! Don't forget to save when making code changes in your IDE or you might not get expected results.

To code during the workshop you can either use your laptop or the Cloud-based IDE Gitpod with everything installed.

Choose ONE of the following (GitPod or Local):

----TODO: FOR GITPOD CHROME EXTENSION-----


GitPod online IDE (recommended)

Here we explain the Gitpod way

βœ” Gitpod is a cloud based IDE based on Eclipse Theia very similar to VSCode. You need to authenticate with your Github account and GitPod will initialize your workspace, building the solution. To initialize your environment click on the Gitpod button in the top right hand corner of your new repository.

Open in Gitpod

βœ” At initialization Gitpod will download dependencies automatically (the node_modules folder should already be there).

Target urls are dynamic and look like https://<your_uid>.<your_region>.gitpod.io/#/workspace/battlestax

Netlify Setup Example

OR

Local IDE

Here we explain how to work locally

+ We assume people working locally are not beginners
+ They should be autonomous to install a development > environment.

Here are the tools you need:

βœ” Clone your BattleStax repository to localhost, use the following command in your terminal to do so:

πŸ“˜ Command to execute

git clone [email protected]:[your_github_id]/battlestax.git

βœ” Move to the proper directory

πŸ“˜ Command to execute

cd battlestax

βœ” Install Battlestax Dependencies. These are specified in the package.json file.

πŸ“˜ Command to execute

npm install

βœ… Step 1b: Check your git remote

First things first. Let's ensure you are working out of the correct repository using git remote -v.

πŸ“˜ Command to execute

git remote -v

Running this command will display the GitHub repository you are working out of.

It SHOULD NOT be using DataStax-Examples.

If it is, please kill the GitPod instance you are working out of and start GitPod from the repository you created earlier using the DataStax-Examples template. This will ensure you are on a happy path to pushing your changes to your production site.

βœ… Step 1c: Configure default remote

We just need to configure the default remote once. Run the below command to set your configuration.

πŸ“˜ Command to execute

git config checkout.defaultRemote origin

βœ… Step 1d: Create a local branch for code changes

Create a local branch named myBranch

We'll create a feature branch to record changes locally and then push to master when we're ready to deploy.

πŸ“˜ Command to execute

git checkout -b myBranch

2. Make a Serverless endpoint using Netlify functions

βœ… Step 2a: Check out the functions folder

Each file in our functions folder represents a REST API endpoint implemented as a serverless function (we'll get to this in a moment). For now, take a look at the helloWorld.js file inside the functions folder.

insert

At this point, this REST API endpoint is stubbed out. You'll need to fill it out with the code below. If we use this as it, it will simply give us back {"hello":"world"}.

πŸ“˜ Code to copy

exports.handler = async (event, context) => {
  return {
    statusCode: 200,
    body: JSON.stringify({ hello: "world" }),
  };
};

βœ… Step 2b: Test the REST API with a browser

Now that our code is ready it's time to run the application and access our "helloWorld" endpoint.

πŸ“˜ Command to execute

npm run dev

This will launch the UI and run the helloWorld function in the background.

Choose ONE of the following (GitPod or Local):


GitPod online IDE

Here we explain the Gitpod way

Since we started the application in the foreground, we'll need to open another terminal window in GitPod to execute the next command. To do so, navigate to Terminal in the toolbar and choose New Terminal from the dropdown.

gitpod new terminal

Using your new terminal, execute the following command to generate your GitPod endpoint and preview the helloWorld serverless function in GitPod's preview window.

πŸ“˜ Command to execute

gp preview "$(gp url 8888)/.netlify/functions/helloWorld"

πŸ“— Expected output

{"hello":"world"}

This is our serverless function giving us back the "Hello World" example.

Notice the port, GitPod generated ID, and the GitPod region in the URL below at each arrow. This should automatically be generated for you when you run npm run dev. Just add /.netlify/functions/helloWorld on to the end in order to get to the correct endpoint. We've already done this for you above, but it's good to understand where the endpoint URL is coming from.

πŸ“— Expected output

test functions output

OR

Local IDE

Here we explain how to work locally

πŸ“˜ Copy and paste into your browser

localhost:8888/.netlify/functions/helloWorld

πŸ“— Expected output

{"hello":"world"}

This is our serverless function giving us back the "Hello World" example.


βœ… Step 2c: Run the existing unit tests

βœ”οΈ Have a look at the /test/helloWorld.test.js file. This tests the helloWorld function to ensure that we get "world" in our response, and hence we would know that the function is working correctly.

There is no need to copy this code, it is already implemented for you

const helloWorld = require("../functions/helloWorld");

it("should return a JSON response", async () => {
  const response = await helloWorld.handler();
  const responseJson = JSON.parse(response.body);
  expect(responseJson.hello).toBe("world");
});

Run the test to try it out:

πŸ“˜ Command to execute

$(npm bin)/jest test/helloWorld.test.js --coverage --setupFiles dotenv/config --testEnvironment node

πŸ“— Expected output

test functions output

3. Merge back to master

βœ… Step 3a. Commit changes back to GitHub

Now that we've updated our code we need to push these changes back to master and kick off an automated deploy in Netlify. We'll do this by committing our changes locally, pushing them up to our repository, then creating a pull request to merge them back to master.

πŸ“˜ Commands to execute

git add functions/helloWorld.js test/helloWorld.test.js
git commit -m "Merging helloWorld into master"
git push --set-upstream origin myBranch

Once you've pushed your changes go back to your repository in GitHub create a pull request to merge your myBranch changes into master. Ensure that you are merging back into your YOUR master branch.

βœ… Step 3b. Create a GitHub pull request for your helloWorld changes

Using Github UI, merge your new branch to the master using a pull request.

βœ”οΈ Select the myBranch branch in github, then click the Pull request button on the right

Netlify Setup Example

βœ”οΈ Verify base displays base: master and compare displays compare: myBranch

Netlify Setup Example

βœ”οΈ Provide a comment and click Create Pull Request

βœ”οΈ Once your tests have passed, click on Merge Pull Request.

Netlify Setup Example

This is going to take a couple minutes as the merge process will install and run application tests automatically using GitHub actions.

βœ”οΈ Click on Confirm Merge

Netlify Setup Example

Congratulations you are done, it should look something like this

Netlify Setup Example

4. Check your deployment in Netlify

At this point you should see that your pull request kicked off a Deploy Preview in Netlify. Once all tests have passed you can confirm your merge.

βœ… Step 4a. Confirm your deployment

βœ”οΈ Browsing Netlify, navigate to Deploys, and see the CI/CD process rolling with our deployments

Netlify Setup Example

Click on any items in the deploy list to see logs and other useful information about your deployments

Netlify Setup Example

Once completed Netlify will automatically push the confirmed changes into production. No need to manually deploy anything separately, just push into your repo and production happens.

Finally, you can check that your new helloWorld function is deployed and accessible from production.

βœ… Step 4b. Confirm your serverless helloWorld endpoint on the internetz

Now that we've sucessfully deployed your helloWorld serverless function simply by merging back to master in GitHub, we should check that it's actually there and working.

βœ”οΈ In Netlify, navigate to Functions in the toolbar, then click the helloWorld function in the list.

Netlify functions

βœ”οΈ Copy the function endpoint from the browser window and paste into a new tab.

Netlify functions endpoint

πŸ“— Expected output

Netlify functions output

Ok, that was arguably a lot of stuff, but we wanted to break down the process at least once. It might feel like a lot of steps on the first couple runs, but as you get used to it the flow becomes quite natural.

  • make changes to your branch
  • push those changes back to GitHub
  • use a pull request to merge the changes back to master
  • CI/CD automatically checks your application using GitHub actions and the Netlify integration
  • confirm merge
  • changes are automatically pushed to production

In the future, we won't break it down quite so much, but feel free to use this section as a reference as we move forward.

Before moving on, take a moment to let this sink in. You just deployed an app with a serverless function to production over a globally supported CDN using a full CI/CD pipeline all by merging your code into master. Boom!

Now let's learn more about Astra and Stargate before moving to the next lab.

🏠 Home

🏁 I - What is the JamStack?

Introduction to the JAMStack Why this is cool ? Introduction to Netlify Want to learn more ? πŸ› οΈ II - Setup and deploy your first app

Create your BattleStax repository Setup Netlify account Summary πŸ› οΈ III - Create your Astra instance

Register and Sign In to Astra Configure and create your database Activate Cassandra awesome πŸ“š IV - What can Netlify do for you

Build, Package, deploy, host Advanced features Netlify Functions Want to learn more πŸ› οΈ V - Expose your "hello world" API

Setup your environment Make a serverless endpoint using Netlify functions Merge back to master Check your deployment in Netlify Summary πŸ“š VI - What are DataStax Astra and Stargate

Introduction to Astra Introduction to Stargate Want to know More πŸ› οΈ VII - Set environment variables in your application

Creating the .env file Explore the API with HTTPie πŸ› οΈ VIII - Set secrets in GitHub for CI/CD

Configure secrets in GitHub Verify your secrets How is this all working ? πŸ› οΈ IX - Set environment variables in Netlify

Set environment variables in Netlify Verify your environment variables Summary πŸ› οΈ X - Implement a CRUD Api in Astra

Creating the insertGame Netlify endpoint Connect to Astra Hook it all together Running TDD tests πŸ› οΈ XI - Verify and Deploy in Netlify

Merge back to master Verify your deployment in Netlify Feel the enormity of your accomplishment Super secret full game option πŸ“š XII - Resources

Clone this wiki locally