Forge repo instructions - 03-access-external-resources-solution

Accessing external resources

We now have a basic UI structure for the issue context together with the placeholder values. Let’s call an external service to get the temperature and other values.

Generate an API token

  1. Sign-up for a free account at API Ninjas and generate an API key as we will be using that in this workshop.

Updating the resolver to make an external API call

  1. If your Forge tunnel is still running, stop it by pressing Ctrl + C.

  2. In your preferred IDE, open the resolver file: src/resolvers/index.js

  3. Create a function called fetchDogInfo right below the resolver definition.

    ...
    const resolver = new Resolver();
    
    const fetchDogInfo = async () => {
    }
    
    
  4. Define the API parameters to be used by the API

    const fetchDogInfo = async () => {
    
      // Hardcoded for now
      const breedName = "chihuahua"; 
      const apiKey = ""; // TODO: Insert your API Ninjas API Token here
      const url = `https://api.api-ninjas.com/v1/dogs?name=${encodeURIComponent(breedName)}`;
    
    }
    
    
  5. Add the snippet to call the API using the fetch client

    const fetchDogInfo = async () => {
    
      ...
    
      const url = `https://api.api-ninjas.com/v1/dogs?name=${encodeURIComponent(breedName)}`;
    
      const response = await fetch(url, {
        headers: { 'X-Api-Key': apiKey },
      });
    
    }
    
    

    Add the import statement for Forge’s fetch client at the top

    import Resolver from '@forge/resolver';
    import { fetch } from '@forge/api';
    
    

    Install the @forge/api package by going to the command line/terminal and running this command

    npm install @forge/api
    
    
  6. Process the API response with basic error logging

    const fetchDogInfo = async () => {
    
      ...
    
      const response = await fetch(url, {
        headers: { 'X-Api-Key': apiKey },
      });
    
      // Handle the negative response of the API call
      if (!response.ok) {
        if (response.status === 429) {
          throw new Error('API rate limit reached. Please try again later.');
        }
        throw new Error(`Dogs API returned status ${response.status}`);
      }
    
      const dogInfo = await response.json();
    
      return dogInfo;
    
    }
    
    
  7. Define the getDogInfo resolver function that the frontend will invoke

    ...
    
    resolver.define('getDogInfo', async () => {
    
      return (await fetchDogInfo());
    
    });
    
    resolver.define('getText', (req) => {
      console.log(req);
      return 'Hello, world!';
    });
    
    

Call the resolver function from the frontend

  1. Open the frontend file: src/frontend/index.jsx

  2. Update the existing getText invocation to call the recently defined getDogInfo

    // This is the old code we'll update
    //useEffect(() => {
    //  invoke('getText', { example: 'my-invoke-variable' }).then(setData);
    //}, []);
    
    useEffect(() => {
      invoke('getDogInfo').then(setData);
    }, []);    
    
    
  3. Use the returned value that was set to data to update the UI in the return statement. Make sure to check if data has value already before accessing its properties.

    return (
      <>
        <Heading size='medium'>Welcome, {data ? data[0].name : '[Loading]'}!</Heading>
    
        <Text>Life expectancy: {data ? data[0].min_life_expectancy : '[Loading]' } – {data ? data[0].max_life_expectancy : '[Loading]' } years</Text>
        <Text>Height: {data ? data[0].max_weight_female : '[Loading]' } inches</Text>
        <Text>Weight: {data ? data[0].max_height_female : '[Loading]' } lbs</Text>
      </>
    );
    
    

    For reference, the sample response looks like this

    [
      {
        "image_link": "https://api-ninjas.com/images/dogs/chihuahua.jpg",
        "good_with_children": 1,
        "good_with_other_dogs": 3,
        "shedding": 2,
        "grooming": 1,
        "drooling": 1,
        "coat_length": 2,
        "good_with_strangers": 2,
        "playfulness": 4,
        "protectiveness": 4,
        "trainability": 3,
        "energy": 4,
        "barking": 5,
        "min_life_expectancy": 14,
        "max_life_expectancy": 16,
        "max_height_male": 8,
        "max_height_female": 8,
        "max_weight_male": 6,
        "max_weight_female": 6,
        "min_height_male": 5,
        "min_height_female": 5,
        "min_weight_male": 4,
        "min_weight_female": 4,
        "name": "Chihuahua"
      }
    ]
    
    

Add the required permission in your manifest file

  1. Open the manifest file: manifest.yml

  2. Add the following section at the bottom of your manifest file

    permissions:
      external:
        fetch:
          backend:
            - address: api.api-ninjas.com
    
    

Deploy the app and update the installation

  1. If your Forge tunnel is still running, close the tunnel by pressing Ctrl + C. This is required before you can do a redeploy and installation upgrade

  2. Deploy the app

    • Be sure you are in your project directory

    • Run the Forge deployment command on your CLI

      forge deploy

  3. The previous deployment will fail as expected due to the added external permissions. To fix that, we need to approve the major app version bump by running this command.

    forge deploy --approve MAJOR_VERSION_RULE
    
    
  4. Since the permission section has been updated in the manifest, we need to upgrade the current installation for the changes to take effect

    • On your CLI, run this command

      forge install --upgrade
      
      
    • Select the site or workspace to upgrade where it was previously installed

    • Answer Y to the prompts

      ? Do you want to continue? Yes
      ...
      WARNING: You are about to install a development app to a production site. If you do not intend to test your app, we strongly recommend that you deploy your app to production and install the production version instead.
      ? Are you sure you want to proceed? Yes
      
      
  5. Go to your Jira instance and open a work item to verify the changes. You should be able to see the updated information coming from API Ninjas.