Home > Articles > Home & Office Computing > The Web/Virtual Worlds/Social Networking

This chapter is from the book

This chapter is from the book

2.4 Creating Your First Service: LoanPaymentService

Using some of the posted samples as guidelines, let’s create a new service. You won’t call an external service here; instead, you’ll build one using JavaScript. A familiar example is a service that calculates one’s monthly mortgage payment based on principal, interest rate, and length of loan (years).

Here’s a summary of the steps you’ll follow.

  1. Create a new service. Give it a name and a description.
  2. Add parameters to the service (optional).
  3. Provide JavaScript code that returns data to the caller.
  4. Add any error types (optional).
  5. Test drive your service and modify as necessary.
  6. Capture example return data (optional).
  7. Publish your service.

Let’s start. To create a service, click 26inline01.jpg at the top of the page and select Service as shown in Figure 2.23. You’ll see a new page that asks you to provide a description of the service. The default service name is NewService, which you should change to something meaningful. Many times, service names end in “Service,” but this is not a requirement. Call the service LoanPaymentService.

Figure 2.23

Figure 2.23 Creating a Service

This service requires three input parameters and returns a single numerical result. Error handling for input validation is handled completely by zembly; we discuss this further in the next section. Here’s the JavaScript that provides the service.

Listing 2.2. LoanPaymentService (JavaScript)

// LoanPaymentService
// Input parameters are all NUMBERs and all Required

var principal = Parameters.principal;
var interest = Parameters.interest;
var interest_rate = interest / 1200;
var years = Parameters.years;

//Perform the calculation
var months = years * 12;
var x = Math.pow(1 + interest_rate, months);
var payment = (principal * x * interest_rate)/(x-1);

return payment.toFixed(2);

Specifying Parameters in a Service

When you create a web service, you tell the service interaction page about the parameters for your service. To add parameters, click Add a new parameter in the Call - Parameters window. You specify a parameter’s characteristics in a dialog box.

When you add a new parameter you choose its type. By using the appropriate type, you take advantage of zembly’s built-in parameter validation. Table 2.1 lists the types supported.

Table 2.1. Parameter Types for Services

Type

Additional Fields

Examples

Binary

-

1101

Boolean

-

true, false

Email

-

info@buildtheweb.org

JSON

-

{"firstName":"John", "lastName":"Smith"}

Key

Keyset Provider

(Depends on provider)

Number (integer, real, or floating point)

Min Value, Max Value

55, 25.3

String

Max Length, Escape value

any string <= Max Length

URI

-

http://www.asgteach.com

XML

-

<firstName>John</firstName>
<lastName>Smith</lastName>

For this service, specify three parameters (principal, interest, and years). Make them all required and Type Number. With Number you also specify the minimum and maximum values. For principal use minimum 10 and maximum 2 million (2,000,000). For interest specify minimum 1 and maximum 20. Finally, for years use minimum 1 and maximum 99. Figure 2.24 shows the Parameter Editor for parameter years.

Figure 2.24

Figure 2.24 Creating and editing a web service parameter

Note that if you make a parameter required, zembly flags an error if the caller doesn’t provide a value. If you want the parameter to be optional, uncheck Must use this parameter in the call.

Once you’ve specified the parameters, you can access them in JavaScript. For example, you access the LoanPaymentService principal parameter with Parameters.principal.

Error Handling

When you detect a problem in your service, error codes can communicate status to the caller. You specify error codes in the service’s Error Codes section. To add an error code, click Add a new error type. Figure 2.25 shows the dialog box that lets you specify a new error type. (You may also edit error codes that you have already defined.)

Figure 2.25

Figure 2.25 Creating and editing web service error codes

The error code, description, and HTTP status code all appear on your web service’s documentation page. Note that you don’t need to define an error code for the LoanPaymentService, since all error handling is performed by the built-in parameter validation.

Testing LoanPaymentService

Once you’ve built a service, you’ll want to test it. Use the Call tab located next to the source editor window. You must provide values for any required parameters and click Test drive now. This calls the service with the parameter values you’ve provided and displays any results (or error codes) in the window. Figure 2.26 shows an example with a successful test.

Figure 2.26

Figure 2.26 Testing a service

Figure 2.27 shows the built-in parameter validation when you provide a value outside the range for parameter years.

Figure 2.27

Figure 2.27 zembly’s parameter validation

Capturing Example Return Data

To help others use your service, you can capture the return data after testing your service. Simply click the Capture example button (as shown in Figure 2.26). zembly creates a new heading on your service’s documentation page and displays the output. This helps users, especially if the return data contains specific formatting (such as XML or JSON data). Figure 2.28 shows an example for LoanPaymentService.

Figure 2.28

Figure 2.28 You can display sample output on your service’s documentation page

Saving Drafts

Each time you edit your code and test drive the service, your current code is automatically saved in a draft for you. zembly displays a small bar to indicate the current draft (the bars are displayed on the right with the most recent modification saved on top of the stack).

You can force a saved draft by clicking the Save Code icon at the bottom of the editor (or typing Ctrl+Alt+S). You can return to any previously saved draft or published version simply by clicking the bar. Also, you can see the timestamp and draft or version number by holding the cursor over the bar. See “Drafts, Versions, and Timelines” on page 42 for a more detailed discussion.

Using the JavaScript Editor

The JavaScript editor color codes key words, comments, and objects. The editor includes icon commands in the lower right window (as shown in Figure 2.29) to save your draft (Ctrl+Alt+S), toggle full screen editing (Ctrl+1), format code (Ctrl+Alt+F), undo editing (Ctrl+Z), redo editing (Ctrl+Y), or create a code snippet (Ctrl+Shift+N). You can also invoke code completion with Ctrl+Space.

Figure 2.29

Figure 2.29 JavaScript editor command icons

Publishing LoanPaymentService

Click the 32inline01.jpg button to publish your service. This is the magic step that zembly provides to make services and widgets available to others. When you publish your service, zembly creates a deployable web service and deploys it in its own managed container. As you modify your service, zembly keeps track of drafts (unpublished edits) and versions (published edits). With each version you are encouraged to specify how the new version has improved (why it is cool).

Calling LoanPaymentService

Once you’ve tested and published your service, you’ll want to call it from another service or widget. The page provides the code you need to call the service from another service, from a widget, or through the browser. However, the easiest way to call your service is to use zembly’s Find & Use feature which automatically adds the code as a template in the editor. The Find & Use feature is context sensitive, so it will import the correct code depending on whether you’re currently developing a widget or service. In addition, with Find & Use you’ll see documentation about the service and its parameters.

Use the following (JavaScript) code to call your service from another service. zembly generates the comments for each parameter from the documentation you provide.

var result = Things.ganderson.LoanPaymentService({
     principal: 0, // The principal of the loan (in dollars)
     interest: 0, // The interest rate (per cent) (e.g., 6.5)
     years: 0 // How long your loan will endure (in years)
 });

Use the following template (JavaScript) code to call your service from a widget.

  Things.callService("ganderson.LoanPaymentService",
{
    principal: 0, // The principal of the loan (in dollars)
    interest: 0, // The interest rate (per cent) (e.g., 6.5)
    years: 0 // How long your loan will endure (in years)
},
{
    onSuccess: function(data) {
        Log.write(data);
    },
    onFailure: function(error) {
        Log.write("Error: " + error.code + " : " + error.message);
    }
});

A third way to call a service is to cut and paste the URL provided on the service page into the address line of your browser. Pasting the URL in your browser address line calls the service from HTTP. You must specify the parameter values in place of each [value] marker. Here is the LoanPaymentService URL with values replacing [value] in the URL.

http://zembly.com/things/2ef3f34205c84fca9b0d91c538fc6a5b;exec
   ?principal=232000&interest=4.5&years=15

Figure 2.30 shows the browser window after calling the LoanPaymentService.

Figure 2.30

Figure 2.30 Calling a service with HTTP using its URL in the browser

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020