15. Building APIs
So far, we've consumed third party APIs. However, a key feature in Flowgear is the ability to publish any Workflow as an API. In this section, we'll walk through how to set up your Site and create & publish a Workflow as an API.
Common use cases include:
- Delivering an Enterprise API that wraps an organization's data structures and business logic to authorized third parties, like customers, vendors, and partners.
- Receiving and acting on webhooks that are notifications of activity in third party apps or services.
- Mobile or Web App Backend as a Service.
- An intelligent proxy that adds business logic, and modernizes, extends, or meters an internal or legacy service.
Building a REST Service
Assigning a Hostname
Each Environment in a Flowgear Site can have a unique Hostname (domain) associated with it. You can view this information from Settings → Site Settings under Environments.
Click ✎ next to an Environment (we'll use the Test Environment) to see the associated host under Hostname.
- Under trial accounts, all hostnames are pre-configured and include your tenant key in the hostname.
- On paid plans, you can choose a custom sub-domain so that your hostname ends with
.flowgear.net. - On certain paid plans, you can specify a completely custom domain. For example, instead of
mycompany.flowgear.net, you can specifyapi.mycompany.com. Note that in these cases, you'll be responsible for making DNS changes and providing Flowgear with a TLS certificate.
Creating an API-Bound Workflow
Flowgear is normally used to publish Workflows as REST APIs (Although, it can also be used to emulate a SOAP service). As we looked at in an earlier section, REST uses the HTTP Method to denote the action to take, whilst the URL is the resource the action should be taken against. REST services also typically use JSON request and response payloads. However, Flowgear doesn't enforce this.
From within the Workflow, you'll be able to configure the HTTP Method and the URL template the Workflow will activate for.
When you need to interact with input parameters, such as those provided in the querystring of a request or the request body itself, you'll add special input Properties to a Variable Bar Node. Similarly, to send a response body back, you'll add special output Properties to a Variable Bar Node.
Read more about Enterprise API and Special Variable Bar Properties.
Authorizing Access
In order for a consumer to invoke a Workflow, it must provide an API Key that has permission to run that Workflow. You can manage API Keys from the left-hand menu. Keys are scoped to a specific Environment. In other words, each key can only be used to invoke a Workflow under one specific Environment. When managing an API Key, you'll also be able to specify exactly which Workflows are permitted to execute based on that key.
Read more about Token Authentication.
Exercise 20: API Query Service
In this exercise, we'll build a Workflow that allows us to query a contact record from a database.
Add
Microsoft SQL Queryto a new Workflow, and rename it toQuery. ConnectStart.Start → Query.Create a Connection for
Queryand use the same credentials given in 09. Working with Databases.Set
Query.Querytoselect top 1 * from contacts where id = @id.Add
Variable Bar, and rename it toInputs.Add a Property on
Inputsnamedid, and set it as an output (i.e. Flow Socket on the right-hand side) with a value of1.Add a Custom Property on
Querynamedid, and connectInputs.id → Query.id.Add
JSON Convert, and connectQuery → JSON Convert.Set
JSON Convert.ActiontoXmlToJson.Connect
Query.ResultXml → JSON Convert.Xml.Add
Variable Bar, and rename it toOutputs.Add a Property on
OutputsnamedFgResponseBody.FgResponseBodyis a special Variable Bar Property that is used to control the response sent by an API-bound Workflow. Instead of typing the name by hand, click+on theVariable Bar, and then clickvnext to the Property name to see a list of special Properties.You can read more about these Properties in Configure Variable Bar.
Connect
JSON Convert.Json → Outputs.FgResponseBody.Add a Property on
OutputsnamedFgResponseHeaders, and set its value toContent-Type: application/json.FgResponseHeadersallows us to provide the set of headers that should be returned to the consumer. The only required header isContent-Type, which advises the consumer of the type of content being returned, known as a mime type.In this exercise we are going to return a JSON document, which uses the mime type
application/json.Open Workflow Settings by clicking
Settings, located just to the right of the Save button.Enable
HTTP Bindingto expand the options. Then, set theHTTP Binding Method(dropdown) toGET, and update theHTTP Binding Path(where you see/path/to/endpoint) to/contacts/{id}.We are configuring the Workflow to be bound to the template
GET /contacts/{id}. In other words, this is aGETrequest (information is being retrieved, rather than changed) and the location is/contacts/{id}.{id}is mapped to theidProperty in the Variable Bar, so when the Workflow runs, the value that was provided will be injected into theidProperty there.Click
Copyto copy the URL template to the clipboard. Then, return to the Workflow Design.Run the Workflow to confirm it's executing successfully, and then save it.
We will now generate an API key to be used with the Workflow.
Open
API Keysfrom the left hand menu. You can do this in a separate browser tab by clicking while holdingCTRL(Windows) or⌘(Mac).In API Keys, click
+ New API Key.Next, set the
API Key TypetoToken Based.Provide the
API Key NameinTest, and add your Workflow under theAssign a Workflowsection. If you named the Workflow20: API Query Service, it should be shown there.Click
✓ Save Changes. An API Key will be generated and shown on screen.Flowgear only stores a cryptographic hash of these keys, rather than the keys themselves. If you lose the key, you'll need to generate a new one by clicking
Regenerate.Open a new browser tab and paste in the URL template you copied from the Workflow design. Replace
{id}out with a number, e.g.2.Add
?auth-key=to the end of the URL, followed by the API Key shown underPrimary Key.Your full URL should look like this:
https://api-test-trialabcd.flowgear.net/contacts/2?auth-key=longapikeytexthereOpen the URL to confirm you're receiving a JSON document back, containing the details of the contact specified in the querystring.
Save and run your Workflow, and then click Submit Exercise to grade it.
Exercise 21: API Update Service
In the previous exercise, we built an API that queries data from an underlying source. In this exercise, we'll accept data from the consumer (i.e. the party invoking the API) and store it in an underlying service.
Add
File Writeto a new Workflow. ConnectStart.Start → File Write.Create and assign a Connection to
File Writethat uses your locally installed DropPoint.Add
Variable Bar, and rename it toInputs.Add a Property on
InputsnamedFgRequestBodyand set its value to:{ "somefield": "somevalue" }Connect
Inputs.FgRequestBody → File Write.Content.Set
File Write.Pathto a location in which the file can be created, e.g.c:\temp\test.json.For this exercise, we're hardcoding a file name so that the content will be replaced each time the Workflow runs.
In a real-world scenario, we could add a
filenameProperty to the querystring, and then dynamically compose a path that includes the filename Property.This would allow us to create a file with a name specified by the consumer. Bear in mind that with this approach, it would be important to test that only expected characters are provided in the file name. For example, if the consumer provided a file name
..\somefile.json, it would resolve toc:\somefile.json. In other words, it would cause a file to be created outside of the folder we expected.Add
Formatter.Set
Formatter.Expressionto the following:{ "result": "ok" }Add
Variable Bar, and rename it toOutputs.Add Properties on
OutputsnamedFgResponseBodyandFgResponseHeaders.Connect
Formatter.Result → Outputs.FgResponseBody.The
Formatteris used to send a hardcoded success response back to the API. In a real-world scenario, we'd build a response based on whether or not data was ingested successfully.Set
Outputs.FgResponseHeaderstoContent-Type: application/json.Open Workflow Settings, enable
HTTP Binding, and set theHTTP Binding MethodtoPOSTand theHTTP Binding Pathto/contacts.Run the Workflow and confirm a file has been created at
c:\temp\test.json.If you receive a DropPoint whitelisting error, you need to adjust your whitelisting rules to allow the file to be created. See DropPoint for more information.
Save your Workflow at this point.
Return to the API Key that you created in the previous exercise and add this Workflow under the
Add a Workflowsection. You may need to refresh the page to see the new Workflow if you've left the tab open. Save the API Key after making this change.
Save and run your Workflow, and then click Submit Exercise to grade it.
Exercise 22. API Test
In the previous exercise, we invoked a Workflow from a browser. This is a convenient way to test because when you open a URL from a browser address bar, the browser will use the HTTP Binding Method GET.
However, for this Workflow we need to send a POST Request. We could achieve this by using a Web Request 2 Node in a new Workflow, but it would be best to use a REST Request.
In this exercise, we'll obtain an OpenAPI definition of our REST Service that we can then use to invoke our API using REST Request.
Go to the Workflows Pane and click the
↓button on the right-side. ChooseDownload OpenAPI Definition, save the file to your computer, and open it in Notepad.Add
REST Requestto a new Workflow.Create a new Connection for
REST Request.In the Connection, set
OpenApiDocumentto the content of the document you downloaded and opened in Notepad.Set
Urlto the hostname of your Site for the Test Environment, e.g.https://api-test-trialabcd.flowgear.net.Set
AuthTypetoBearer.Set
AccessTokento the API Key you generated earlier. If you have lost the Key, go back to the API Key screen and clickRegenerate.Save the Connection, then click
Refresh Metadata(You may need to scroll down to see this button).Back in the Workflow, click
v → Choose Sampleon theREST RequestNode. You should see the two API Workflow exercises.Change the value of
somefieldtosomeothervalueinREST Request.Request.Choose the
21. API Update ServiceNode Sample.Run the Workflow and confirm that the
ResponseCodeProperty shows200.
Save your Workflow and run it, and then click Submit Exercise to grade it.