Skip to content

LAB3_Expose your "hello world" API

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

⚒️ Expose your "hello world" API

Exercise time: ~20 minutes

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
  5. Summary

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):


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 follow the instructions below.

✔ Open a new tab in your browser and paste in the following partial URL. Do not submit the page just yet.

📘 URL to copy

gitpod.io/#

Paste in Gitpod url

✔ Now, go to YOUR battlestax repository and copy its URL.

Copy your repo

✔ Finally, paste your repo URL at the end of the gitpod URL combining the two and hit enter to submit the page.

Gitpod full url

Once started your page should look something like this.

Gitpod full url

Notice the blue cube. You may also see some messages about downloading images. It might take a minute for the environment to startup, but if you are seeing this you should be good to go. Move on to the next step.

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 git@github.com:[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.

Ensure you are in the battlestax directory before running the following commands.

📘 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.

NOTE: BattleStax uses both ports 3000 and 8888. If you are running this locally on your machine, you might want to kill anything using the ports before starting the application. GitPod users should not have any conflicts.

📘 Command to execute

npm run dev

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

GitPod users, you might notice a frowny face image like below. Don't worry! This is not an issue and we'll be previewing our helloWorld function here in just a moment.

insert

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

helloWorld test js

Run the test to try it out: NOTE: Local users may need to open another terminal to run the following test.

📘 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.

Ensure you are executing commands from the battlestax directory.

📘 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

Feel free to 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 successfully 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.

You may need to use your browser back button if you checked out some logs from the previous step.

Netlify functions

✔️ Copy the function endpoint from the browser window and paste into a new tab.

Netlify functions endpoint

📗 Expected output

Netlify functions output

5. Summary

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.

Clone this wiki locally