Course menuForge Cloud

Level 1 · Lesson 4

Look up the car

Goal of this lesson

Write a small code file that asks API Ninjas what a car model comes in, have the resolver use it, let the card ask for it, and add API Ninjas to the app’s approved services.

About 35 min7 steps

Behind, or starting here? Download the code as it should be before this lesson, or in the course workspace run course-catch-up level-1/after-02-work-from-your-laptop in the folder above your app. It offers to bring your own app folder to this point and keeps its app id (the id: line in manifest.yml, which links the code to your app on the site), so it stays the same app. Your old files are kept in a copy next to it.

This is the round trip the whole course is built on:

  • The card asks for the car.
  • The resolver in the cloud takes the key from the key safe and asks the car data service.
  • The card shows the answer.

The steps below build this trip one piece at a time: first the code that asks API Ninjas, then the resolver and the card, then the approval that lets the call out.

Car details cardin the browserYour resolverin the cloudAPI Ninjasoutside Atlassianthe car?this car, pleasewhat it comes inthe answer1234the key stays here

See this trip on the Level 1 chart: its first chapter, from the step where the card sends its request, shows exactly these four arrows.

For now the resolver always looks up a BMW 3 Series. Lesson 6 makes it read the car from the repair task.

Step 1: Add Forge’s API package

Functions reach the outside world through @forge/api, Forge’s own package (a bundle of ready-made code) for fetch, which calls a web address, and for the Jira and Confluence APIs. Install it in the app folder:

RunTerminal
npm install @forge/api

npm may print many lines starting npm warn, and finish with a count of “vulnerabilities”. Both are normal for this course: they are npm’s notes about the packages it downloaded, not about your app or your site. Don’t run npm audit fix, which it may suggest; it can change package versions the course relies on.

npm writes this line into package.json for you. The version numbers in your file may differ from the ones shown, because templates and packages are updated over time; only the new @forge/api line matters:

Editpackage.json

npm install @forge/api writes this line for you.

"eslint-plugin-react-hooks": "^4.6.0"
},
"dependencies": {
Added: "@forge/api": "^8.2.0",
"@forge/bridge": "^7.1.0",
"@forge/react": "^12.3.0",
"@forge/resolver": "^2.0.0",

Why: External API

Stuck?2 common problems, and their fixes
  • “Cannot find module @forge/…”

    The code imports a package that is not installed. Install the one named in the message, then deploy:

    RunTerminal
    npm install @forge/api
    forge deploy
    Open in the FAQ
  • I added an npm package

    Install it so package.json lists it, then deploy. Forge bundles what package.json and your imports name:

    RunTerminal
    npm install @forge/api
    forge deploy
    Open in the FAQ

Step 2: Write the car data file

Outside Atlassian

External APIin the workshop: the car data service

An API is a door into another company’s system that is made for programs instead of people. A website shows you pages with buttons; an API answers questions that code sends to a web address, in a form code can read. Jira has one too: when an automation rule uses Send web request, or a Marketplace app reads your work items, it goes through Jira’s REST API.

An external API is any such service outside Atlassian that your functions call over HTTPS. Here it is API Ninjas’ Cars API. Your code sends it a make and a model, plus your key in the X-Api-Key header (a labelled extra line sent along with a web request, so the key does not sit in the address). It answers with JSON, a plain-text format for data that JavaScript reads directly. Only your functions call it, never the browser, so the key never leaves the cloud.

In the workshop Workshops pay for a service that knows the details of every car model, using an account key.

Create the folder src/cars/ and a new file in it, apiNinjas.js. This is the first time you make a new file:

This file has one purpose, which other files can borrow: it knows how to talk to API Ninjas and nothing else. Developers sometimes call a file like this a module, but the course keeps that word for the modules in manifest.yml, the pieces your app adds to Jira, such as the panel. Here it is simply the car data file; nothing new appears in manifest.yml or in Jira for it. Think of it like a shared workflow: you set it up once, several projects use it, and when it needs to change, you change it in one place.

New filesrc/cars/apiNinjas.js

A new file that knows how to talk to API Ninjas.

Added: import { fetch } from '@forge/api';

Borrow fetch, the tool that calls a web address, from Forge’s own package.

Added:
Added: // The car data service: API Ninjas' Cars API. The caller passes the key in after
Added: // reading it from an encrypted variable, so it never appears in code or in the browser.
Added: // On a free key only /v2/carfacets answers: for a make and model it returns, for each
Added: // facet asked for, the values that model comes in, each with a count, most common first.
Added: const FACETS_URL = 'https://api.api-ninjas.com/v2/carfacets';

The address of the one API Ninjas endpoint this app asks. const gives a value a name that never changes.

Added: const FACETS = ['year', 'fuel', 'transmission', 'drive', 'cylinders', 'badge'];

The six facets to ask for, as a list. Square brackets make a list.

Added:
Added: export async function findCar(make, model, apiKey) {

The function other files call. export lets them borrow it; the three names in brackets are what the caller hands in.

Added: if (!apiKey) {

If no key was handed in (! means “not”), stop at once with a sentence that says how to fix it.

Added: throw new Error('No API Ninjas key. Set it with forge variables set --encrypt, then deploy again.');
Added: }
Added: const params = new URLSearchParams({ make, model, facets: FACETS.join(',') });

Turn the make, the model and the facet list into the part of a web address after the ?, such as make=BMW&model=3+Series.

Added: const response = await fetch(`${FACETS_URL}?${params}`, {

Send the question to API Ninjas and wait for the answer. ${…} drops a value into the text.

Added: headers: { 'X-Api-Key': apiKey },

Send the key along on its header line, not in the address.

Added: });
Added: if (response.status === 429) {

429 means “too many questions”: stop with a sentence that says to try again later.

Added: throw new Error('The car data service is busy (rate limit). Try again in a minute.');
Added: }
Added: if (!response.ok) {

Any other answer that is not OK: stop, and pass on the status code and the service’s own message.

Added: // Premium-only endpoints answer 400 with {"error": "..."}: pass that message on.
Added: const body = await response.json().catch(() => ({}));
Added: throw new Error(`The car data service answered ${response.status}${body.error ? `: ${body.error}` : '.'}`);
Added: }
Added: return toCar(make, model, await response.json());

The answer was OK: read its JSON and let toCar turn it into the card’s format.

Added: }
Added:
Added: // The service sends codes; the card shows words.
Added: const LABELS = {

A small dictionary: on the left the code the service sends, on the right the word the card shows.

Added: gasoline: 'Petrol',
Added: diesel: 'Diesel',
Added: hybrid: 'Hybrid',
Added: electric: 'Electric',
Added: lpg: 'LPG',
Added: manual: 'Manual',
Added: automatic: 'Automatic',
Added: dual_clutch: 'Dual-clutch',
Added: automated_manual: 'Automated manual',
Added: cvt: 'CVT',
Added: fwd: 'Front-wheel drive',
Added: rwd: 'Rear-wheel drive',
Added: awd: 'All-wheel drive',
Added: '4wd': 'Four-wheel drive',
Added: };
Added: const label = (code) => LABELS[code] ?? code;

Look a code up in the dictionary. ?? means “or, if it isn’t there”: an unknown code is shown as it is.

Added:
Added: // Turn the service's format into the one the card uses.
Added: function toCar(make, model, facets) {

Turn the service’s answer into the shape the card uses. No export: only this file uses it.

Added: const values = (facet) => (Array.isArray(facets?.[facet]) ? facets[facet] : []).map((entry) => String(entry.value));

A small helper: for one facet, give back just the values, such as gasoline and diesel, without their counts. A missing list counts as empty.

Added: // An unknown car is not an error: every list comes back empty.
Added: if (FACETS.every((facet) => values(facet).length === 0)) return null;

If every list is empty, the service does not know this car: give back null, “no car”.

Added: // Each year is when a generation started, not a model year, so show only the first.
Added: const years = values('year').map(Number).filter(Number.isFinite);

Turn the years into numbers and drop anything that isn’t one.

Added: return {
Added: make,
Added: model,
Added: since: years.length ? String(Math.min(...years)) : '',

The earliest year, if there is one; otherwise nothing. ? : is a short if/else: “is there a year? then this, else that”.

Added: fuel: values('fuel').map(label),

The fuel codes, each turned into a word through the dictionary. The next two lines do the same for gearbox and drive.

Added: transmission: values('transmission').map(label),
Added: drive: values('drive').map(label),
Added: cylinders: values('cylinders'),
Added: versions: values('badge').slice(0, 5),

Only the first five badges, the most common ones.

Added: };
Added: }

Why: External API · Environment variable

API Ninjas doesn’t say how many free questions you may ask per minute. If the card later says the service is busy, wait a minute and reload.

You don’t need to read every line. The file does four things, and the sketch below follows one trip through it.

A sketch with made-up numbers. The real answer is written as JSON text; it is drawn here as lists so it is easier to read.

It is handed the key. findCar does not read the key itself. Whoever calls it passes the key in, so this file never knows where secrets live. In this app the resolver hands it over, in the next step.

It asks a question. API Ninjas has several addresses, each answering one kind of question. Developers call each one an endpoint. /v2/carfacets is the one that answers “what does this model come in?”, and the only one a free key may use. The code adds the make, the model and the six facets it wants to the address, and sends the key along in the header.

A facet is one property of a car, such as its fuel type, that the service groups its cars by and then counts. You already know the idea from Jira: a dashboard gadget that groups a filter’s work items by Priority shows each priority with how many work items have it. API Ninjas does the same with every BMW 3 Series it knows, once per facet.

Your Jira dashboard

Work items in the filter, by Priority

API Ninjas

Every BMW 3 Series it knows, by fuel

A sketch with made-up numbers. Priority is a field on a work item; fuel is a property of a car.

The six facets the code asks for:

  • year: the years a new generation of the model came out.
  • fuel: what it runs on, such as petrol, diesel or hybrid.
  • transmission: the gearbox, such as manual or automatic.
  • drive: which wheels the engine turns, such as the rear wheels or all four.
  • cylinders: how many cylinders the engine has.
  • badge: the model codes on the back of the car, such as 320d.

It checks how the answer went. Every answer on the web starts with a three-digit status code that says how the request went. If you have looked at the audit log of a Send web request rule, you have seen one. 200 means OK: the service understood and answered. Codes in the 400s mean the request was refused: 400 for a question this key is not allowed to ask, 401 or 403 for a key the service does not accept, and 429 for too many questions in a short time. When the answer is not OK, findCar throws an error, which means it stops and reports the problem in a plain sentence. Lesson 5 shows that sentence on the card.

When the answer is OK, the rest of it is the data: one list per facet, and in each list one entry per value, with how many cars have that value, the most common first.

An unknown car is not an error. Ask about a car the service does not know, such as a typo like “BMW 3 Seires”, and it still answers 200, with every list empty. It is like a JQL search that matches nothing: Jira doesn’t show an error, it shows no results. toCar notices that every list is empty and returns null. In code, null means “nothing here, on purpose”, much like a field on a work item that says None. Here it stands for “no car found”.

It turns the answer into the card’s words. The service sends short codes, such as gasoline and rwd. toCar turns them into words a person reads, such as Petrol and Rear-wheel drive. It keeps the five most common badges as the car’s versions. From the year list it takes the earliest year and shows it as Since. Each year in that list is when a new generation started, not a model year, so the card shows only the first.

One file to change. Because everything about API Ninjas sits in this one file, switching to another car data service later means changing only this file. Level 2 reuses it as it is.

Stuck?One common problem, and its fix
  • I changed code in src/

    With forge tunnel running on your own computer, save the file and reload the Jira page: the tunnel serves your laptop’s code. Without the tunnel, or in a codespace in your browser, deploy:

    RunTerminal
    forge deploy

    The site picks up the new version on its own. You do not need to install again.

    Open in the FAQ

Step 3: Look up one car in the resolver

The template’s resolver answers getText. Replace it with getCar, which takes the key from the key safe and looks up a BMW 3 Series:

Editsrc/resolvers/index.jsChange 1 of 2

Bring in the car data file.

import Resolver from '@forge/resolver';
Added: import { findCar } from '../cars/apiNinjas';

Borrow findCar from the file you just wrote, apiNinjas.js in the cars folder, so this file can call it. ../ means “go up one folder first”, out of resolvers and into src.

const resolver = new Resolver();
Editsrc/resolvers/index.jsChange 2 of 2

Replace getText with getCar, which looks up a BMW 3 Series.

const resolver = new Resolver();
Removed: resolver.define('getText', (req) => {
Removed: console.log(req);
Removed: return 'Hello, world!';
Added: resolver.define('getCar', async () => {

Give the card a question it can ask by name, getCar. async means the answer takes a moment, because it waits for API Ninjas.

Added: const make = 'BMW';

For now the car is fixed. Lesson 6 reads it from the repair task instead.

Added: const model = '3 Series';
Added: const car = await findCar(make, model, process.env.API_NINJAS_KEY);

Ask API Ninjas through findCar, handing it the key from the key safe. await waits here until the answer is back.

Added: return { query: `${make} ${model}`, car };

Send the card two things: what was asked (“BMW 3 Series”), and the car that came back, which is null when nothing was found.

});
export const handler = resolver.getDefinitions();

Why: Resolver · Environment variable

What the new lines do, in plain words:

  • process.env.API_NINJAS_KEY is the encrypted variable from lesson 3: the resolver takes the key out of the key safe and hands it to findCar.
  • async and await mean “this takes a moment, wait for the answer before going on”. Asking API Ninjas is a trip across the internet, so the resolver waits for it, the way an automation rule waits for a web request before its next action.
  • The resolver returns both what it looked for (query, here “BMW 3 Series”) and the car. If the service finds nothing, the car is null, and the card can still say which car it asked about.
Stuck?One common problem, and its fix
  • The card says “No API Ninjas key”

    The variable is missing in this environment, or you have not deployed since setting it:

    RunTerminal
    forge variables set --encrypt API_NINJAS_KEY
    forge deploy

    With forge tunnel running, your laptop runs the code, so the key has to be in your shell as FORGE_USER_VAR_API_NINJAS_KEY. In bash or zsh, read -s FORGE_USER_VAR_API_NINJAS_KEY && export FORGE_USER_VAR_API_NINJAS_KEY asks for it without echoing it.

    Open in the FAQ

Step 4: Ask for the car from the card

The card asks for getCar when it opens and fills in the sample layout with the answer:

Editsrc/frontend/index.jsxChange 1 of 5
  • Bring back the hooks and invoke.
  • Ask for getCar when the card opens.
  • Show what came back.
Removed: import React from 'react';
Added: import React, { useEffect, useState } from 'react';

Borrow two more React tools: useState, the card’s memory, and useEffect, for something to do when the card opens.

import ForgeReconciler, { Heading, Inline, Lozenge, Stack, Text } from '@forge/react';
Editsrc/frontend/index.jsxChange 2 of 5
import ForgeReconciler, { Heading, Inline, Lozenge, Stack, Text } from '@forge/react';
Added: import { invoke } from '@forge/bridge';

Borrow invoke, the way a card asks its resolver for something.

const App = () => {
Editsrc/frontend/index.jsxChange 3 of 5
const App = () => {
Added: const [result, setResult] = useState(null);

Give the card a memory called result, empty at first. setResult puts something in it, and the card redraws.

Added: useEffect(() => {

Do what is inside once, when the card opens.

Added: invoke('getCar').then(setResult);

Ask the resolver’s getCar, and when the answer arrives (then), keep it in result.

Added: }, []);
Added: const car = result?.car;

Take the car out of the answer. ?. means “if there is an answer yet”; before that, car stays empty.

return (
<Stack space="space.200">
<Inline space="space.100" alignBlock="center">
Editsrc/frontend/index.jsxChange 4 of 5
return (
<Stack space="space.200">
<Inline space="space.100" alignBlock="center">
Removed: <Heading size="medium">BMW 3 Series</Heading>
Removed: <Lozenge>Petrol · Diesel</Lozenge>
Added: <Heading size="medium">{car ? `${car.make} ${car.model}` : 'Loading...'}</Heading>

The heading shows the make and model once the car is there, and Loading... until then. Curly brackets put code inside the layout.

Added: {car && <Lozenge>{car.fuel.join(' · ')}</Lozenge>}

Only once there is a car (&&), show its fuel types in a tag, with a dot between them.

</Inline>
Editsrc/frontend/index.jsxChange 5 of 5
</Inline>
Removed: <Text>What the car data service knows goes here.</Text>
Added: <Text>{car ? `Since ${car.since}` : ''}</Text>
</Stack>
);
};

Why: invoke()

What the new lines do, in plain words:

  • invoke('getCar') is the card asking the resolver for the car, by the name the resolver gave it. It is the same trip as getText in lesson 1, now with a real question.
  • useEffect(…, []) means “do this once, when the card opens”. Without it the card would ask again every time it redraws.
  • useState is the card’s short-term memory. The answer goes into result when it arrives, and the card redraws itself with it.

Until the answer arrives, car is empty, so the heading says Loading… for a moment. Lesson 5 replaces that with a proper waiting state.

Step 5: Add API Ninjas to the approved services

Declared in manifest.yml

Egress permissionin the workshop: approved services

Forge blocks every call from a function to an outside host unless the manifest lists it. Backend calls go under permissions.external.fetch.backend. List the host name only, without https:// or a path. Each host you add is shown to the admin who installs the app.

In the workshop The workshop only uses the outside services on its approved list.

Further reading, optional: Atlassian docs on Runtime egress permissions (opens in a new tab)

See this on the Level 1 chart, in the step that calls API Ninjas.

Your functionfetch(…)api.api-ninjas.comany other hostlisted: goes throughnot listed: stoppedmanifest.ymlexternal: fetch:backend: [hosts]

Without this, the code is right and the call still fails. Add the host at the end of manifest.yml:

Editmanifest.yml

Allow calls to API Ninjas from your functions.

memoryMB: 256
architecture: arm64
id: ari:cloud:ecosystem::app/<your-app-id>
Added: permissions:

The manifest’s list of what the app may do. Each level of spaces goes one step deeper.

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

The one outside host your functions may call. Host name only, with no https:// and no path.

Why: Egress permission · Major version

Stuck?2 common problems, and their fixes
  • The logs show a fetch to api.api-ninjas.com was blocked

    API Ninjas is not on the approved list, or the installation is still on the old major version. Check permissions.external.fetch.backend in manifest.yml, then approve and upgrade.

    Open in the FAQ
  • After changing manifest.yml, forge lint or forge deploy reports an error in the manifest

    Most often the spaces at the start of the lines are off. In manifest.yml those spaces matter: they show what belongs inside what, the way an outline does. Every line you add must start with exactly as many spaces as the line it sits next to in the lesson’s change, and it must use spaces, not tabs. Compare your file with the change, line up the new lines, save, and run:

    RunTerminal
    forge lint

    If you are still stuck, download the code after the lesson (the link at the end of each lesson) and compare its manifest.yml with yours.

    Open in the FAQ

Step 6: Deploy and sign the new approval

Declared in manifest.yml

Major versionin the workshop: extra work needs a new approval

A deploy that asks for more than the last version could, such as a new outside host or a new scope, becomes a new major version. The CLI stops and asks you to approve it, so nobody widens an app’s permissions by accident. Code-only changes stay minor and reach sites by themselves.

In the workshop A workshop asks before doing more than was signed off; a deploy with new permissions stops and asks too.

Further reading, optional: Atlassian docs on Environments and versions (opens in a new tab)

Lives on your laptop

forge install --upgradein the workshop: the site admin signs the new approval

forge install --upgrade moves an existing installation onto the newest major version, so the site grants the new permissions. Until you run it, the site keeps running the old version with the old permissions, even though the deploy succeeded.

In the workshop Until the site admin signs, the site keeps working under the old approval.

Further reading, optional: Atlassian docs on forge install (opens in a new tab)

Stop the tunnel if it is running, then deploy:

RunTerminal
forge deploy

It stops on purpose and names the rule to approve. The end of its output is red and says the deploy failed: that is the stop you expect, not something you broke.

You should seeExampleThe wording may differ a little between CLI versions.
$ forge deploy
…
⚠ 1 issue (0 errors, 0 warnings, 1 approval)
Issue found is not automatically fixable with forge lint.
The deploy failed due to 1 approval requested. Run forge deploy --approve MAJOR_VERSION_RULE …

Approve it, then upgrade the installation on your site:

RunTerminal
forge deploy --approve MAJOR_VERSION_RULE
forge install --upgrade

The upgrade shows a small table with one row per installation (environment, site, product and version, marked Out-of-date). Move to the row for your developer site with the arrow keys and press Enter. It then asks two questions. Answer both with y and Enter: they end in (y/N), which means pressing Enter alone answers No and cancels the upgrade.

  1. Your app will be upgraded and additionally exchange data with the following urls: api.api-ninjas.com. Do you want to continue? This is the new permission you are signing for.
  2. The warning that you are installing a development app on a production site, as in lesson 1: Are you sure you want to proceed?
You should seeExampleYour site, versions and the table's layout differ.
$ forge install --upgrade
? Select an installation: (Use the Enter key to select)
❯ development   your-name.atlassian.net   Jira   2 (Out-of-date)
Your app will be upgraded and additionally exchange data with the following urls:
  - api.api-ninjas.com
? Do you want to continue? (y/N) y
WARNING: You are about to install a development app to a production site. …
? Are you sure you want to proceed? (y/N) y
✔ Upgrade complete!
Stuck?3 common problems, and their fixes
  • Deploy stops after a permission change

    That is expected, not an error. A new scope or outside host makes a new major version, which you approve. Then move each installation onto it. On your own developer site you are the admin, so you accept it yourself:

    RunTerminal
    forge deploy --approve MAJOR_VERSION_RULE
    forge install --upgrade
    Open in the FAQ
  • The tunnel is running while I deploy or upgrade

    Stop it with Ctrl+C first, then deploy or upgrade, then start it again. While the tunnel runs, Jira runs the code on your laptop instead of your last deploy, so if you deploy with it running you cannot tell which version you are testing. Changes to the manifest only reach the site through a deploy, never through the tunnel.

    Open in the FAQ
  • forge install warns about installing a development app on a production site

    The CLI warns because the development version of an app changes often and is not meant for sites where people do real work. If the site is your own developer site, that is exactly what it is for: answer yes. If it is a site your company or team uses, answer no and install on a developer site instead.

    Open in the FAQ

Step 7: Open the BMW 3 Series repair task

Reload the BMW 3 Series repair task. After a moment the card shows the make and model, the fuel types it comes in, and the year it first came out.

You should see, on the work itemExampleAn example: the service’s data changes over time.

Car details

BMW 3 Series Petrol · Diesel · Hybrid

Since 1987

If the heading stays on Loading…, the call failed. forge logs shows why; lesson 5 makes the card say it too.

Stuck?4 common problems, and their fixes
  • The card says “No API Ninjas key”

    The variable is missing in this environment, or you have not deployed since setting it:

    RunTerminal
    forge variables set --encrypt API_NINJAS_KEY
    forge deploy

    With forge tunnel running, your laptop runs the code, so the key has to be in your shell as FORGE_USER_VAR_API_NINJAS_KEY. In bash or zsh, read -s FORGE_USER_VAR_API_NINJAS_KEY && export FORGE_USER_VAR_API_NINJAS_KEY asks for it without echoing it.

    Open in the FAQ
  • The card says “The car data service answered 400” (or 401, 403)

    A 400 that says the endpoint is “only available to premium subscribers” means the code calls a Cars endpoint a free key cannot use, such as /v2/cars. Check that src/cars/apiNinjas.js calls /v2/carfacets.

    A 401 or 403 means API Ninjas did not accept the key. Copy it again from your API Ninjas account, set it again with forge variables set --encrypt API_NINJAS_KEY, and deploy.

    Open in the FAQ
  • The card says “The car data service is busy”

    API Ninjas answered 429: too many requests for your plan in a short time. Wait a minute and reload the work item.

    Open in the FAQ
  • The logs show a fetch to api.api-ninjas.com was blocked

    API Ninjas is not on the approved list, or the installation is still on the old major version. Check permissions.external.fetch.backend in manifest.yml, then approve and upgrade.

    Open in the FAQ

Compare with yours: download the code after this lesson.

Type at least two letters.