Web API and simple mobile app
ema.doc
EMA
TM352 Web, mobile and cloud technologies
EMA
Copyright © 2019 The Open University
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, transmitted or utilised in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without written permission from the publisher.
WEB 058254
3.1
Contents
· EMA
· Scenario
· Part 1 A web interface to the API
· Scenario
EMA
Start of Box
This end-of-module assessment (TM352 EMA) must be submitted by 12 noon (UK local time) on 16 September 2019.
End of Box
This module uses the online TMA/EMA service for submission of the EMA. You can access this service through your StudentHome page.
A link to the booklet Information for Students Submitting Examinable Work Electronically will be sent to you approximately six weeks prior to the EMA submission cut-off date by the university’s Examinations and Assessment department. This will give you formal guidance about submitting your EMA, and you should read it carefully. Submission of your EMA is not the same as submission of your TMAs, and you must follow the instructions given in the booklet.
This EMA takes the place of an examination and so is also referred to as the ‘examinable component’. The EMA makes up 50% of the assessment for this module and it is split into the following three sections:
1. the development of a demonstration API and basic web application (20%)
2. the development of a demonstration mobile application (40%)
3. a discussion of the future development of the applications and their implications (40%).
The EMA documentation is presented across two documents:
· The EMA scenario and questions
· EMA Database and API document which provides an overview and details of the EMA database, its content and the API with which it can be accessed.
Please ensure you read both documents in conjunction with one another before embarking on your work for the EMA.
What to submit
It is a good approach to have a separate folder for your answers to each part and then to zip these folders to create a single EMA zip file for submission. As all the material in a folder is specific to that question, you should use three separate Solution Document files: one per part.
The separate Solution Documents should use the following naming convention: 'oucu_solution_partn'
Part 1
· For this part your answer will comprise a written Solution Document 'your oucu_solution_part1' and a completed NetBeans project.
Your Solution Document should be a .doc, .docx or .rtf file that can be opened in Microsoft Word. Be sure to put your name, your personal identifier, the module code, the assignment number and the date on the title page of your Solution Document. It is also useful for the marker if you include this information as part of the header or footer of your document.
You are also required when submitting your completed NetBeans project to make sure that your NetBeans project is cleaned. This means that the project takes up minimal space. To do this, right-click on the project in the Projects window and choose Clean Project (not Clean and Build Project).
Put everything (your Solution Document and completed NetBeans project) in a single folder for part 1, and then zip it up before submitting it along with the other parts to the online TMA/EMA service.
Part 2
· For this part your answer will consist of a Solution Document, 'your oucu_solution_part2' which contains your description of three functional requirements that you have implemented , along with a guide to installing and running your app. You must also submit your Cordova project’s www directory, ensuring that all your HTML and JavaScript is included. Put these elements together into a folder for part 2 to zip up as part of your EMA submission.
When you submit your mobile project work to the eTMA system, a full project directory may exceed the file size allowed. For this reason, and for simplicity, you are asked to submit just your ‘www’ project directory, which should contain all of your source HTML and JavaScript.
Part 3
· For this part you should submit a Solution Document 'your oucu_solution_part3' that discusses the four issues you have selected.
Your complete zipped EMA file must be no more than 10 MB. If your file is bigger than this then you may need to compress any images you may have used in order to reduce the overall size.
Please note that the cut-off for this assignment is 12 noon UK time. You can find guidance on using the online TMA/EMA service via StudentHome.
Because the EMA is equivalent to an exam, your marks will not be returned to you via the TMA/EMA service. Your EMA will be marked in the same way as an exam and you will be informed of your results, by letter, approximately 2–3 months after the submission date.
The EMA includes use of a database, which you may not be familiar with. You do not have to interact directly with the database however, because a REST API is used. You therefore only need to examine the database tables and sample data, which are quite simple to understand and these are described in a separate document.
Experience has shown that students generally do much better if they read the EMA, understand the requirements and make a plan of work as a schedule so that it is clearer how the work will be completed in time for the submission deadline.
Start of Box
Plagiarism
It is imperative that you avoid plagiarism, as it is a form of cheating. If you do plagiarise, then you won’t simply lose marks: instead, your work will be referred for further disciplinary action. If you are in any doubt as to what constitutes plagiarism, please refer to the University guidelines or see the Module Guide.
End of Box
Extensions to the submission date for your examinable work are not available. If you are not able to submit your completed examinable work by the submission cut-off date, then please refer to the Information for Students booklet to see what options may be available to you.
Scenario
Start of Box
Note that although you have met MegaMaxCorp in earlier TMAs, the emphasis in the company’s profile and their desired direction have changed in some ways. You should therefore review the scenario carefully.
End of Box
The MegaMax Corporation sells widgets worldwide to large companies and small businesses and intends to develop its offering so that it can sell to the public, through the web and via a mobile sales force. Naturally, their stock situation is constantly fluctuating, as sales and deliveries are made, so they retain accurate information in a database. Specifically, they retain information on:
· products and prices
· special offers
· existing clients (or ‘customers’)
· salespeople – including their names, addresses, and contact details
· stock types and levels.
These data are stored centrally, with varying levels of security, permissions and access. This allows access for:
· internal management and report generation
· internal sales staff who visit established clients
· public access, e.g. for purchasing products via the web.
Prices are reviewed and altered on a day-to-day basis, with special deals regularly being made available on certain products, and to favoured clients. The database is currently hosted internally, with selected fields made available to web clients;, however, the company is currently considering migrating much of its data to cloud storage.
The company currently maintains a conventional set of web pages through which members of the public may obtain information about products, prices and deliveries, and through which they may place or view orders. These obviously interface with the stock, price and other data.
In addition to conventional ordering from clients across the internet, the company retain a large and scattered sales force in the UK and worldwide, working generally with large corporations and businesses that make massive orders. These salespeople are given broad responsibility to:
· take orders from existing clients
· recruit new clients
· negotiate and strike special deals that are not currently available centrally with new and existing clients.
The company thereforerequires an app for their sales force to use on a range of mobile devices. The app will provide read access to the company databases through a REST API to find:
· current customer data
· customer order history
· current price data
· currently available special deals.
The app will also have write access to the databases via a REST API to register:
· new customer details
· updates to existing customer details
· orders (which may include special price deals).
These functions will all be achieved through a set of forms displayed on a mobile device. The app may also provide some client-side processing to assist the salesperson in preparing orders, etc. (e.g. VAT calculations and totalling).
Moreover, since the company tracks the locations of all members of their sales force, the app can use the geolocation capacities of the device on which it is running to report its position whenever access is made to the company’s central servers (and/or cloud storage), as well as recording the location when a sale is made. The geolocation facility can also be used with externally available map data to plot and cost routes between clients.
To demonstrate the potential benefits and risks of using REST, web and mobile technologies, MegaMax would like to see some simple prototypes developed as rapidly as possible to show how these technologies might work together and to act as a focus for discussion and future development for the company.
It is important to the company that the potential to develop a new website and a mobile application are demonstrated with both applications being based on the same instance of the company sales database. To this end, the company is considering employing a REST API for the database and have already developed an initial limited prototype of the API.
It is thought that under this scheme (shown in Figure 1) a set of web pages would provide both the website for online ordering by clients, and a mobile app for the sales staff to place orders. Both applications would access the sales database via a single REST API. The website will call the API over the internet, while the mobile app, used by the mobile sales force, will make calls to the API over a mobile phone network. The API itself and the website will both run on web servers. The API will translate requests from applications into SQL operations on the database and will then return the appropriate data or an error message if something goes wrong.
Start of Figure
Figure 1 Components of web and mobile applications
End of Figure
The prototype database and REST API are described in a separate document ‘EMA Database and API’.
Part 1 A web interface to the API
Before starting this question, you may find it helpful to review some of the Block 1 NetBeans activities, in particular NetBeans Activity 9.
Also if you did not complete NetBeans Activity 13, we recommend that you read the first page, which introduces the idea of JavaServer Faces, and the model–view–controller (MVC) architecture that is used in this part. If you did complete NetBeans Activity 13, note that in this EMA you will not need to use ‘pass-through elements’.
There is a provided skeleton NetBeans web project, EMAP1. You will need to download and unzip this project before starting work on this question. Later you will need to zip your completed project and completed Solution Document and return them as part of this EMA.
Scenario
You have been asked to complete a web page-based interface to the API that will allow users to view their current orders and place new orders.
Remember that there is no log in operation and, as usual with a REST API, no user state is maintained from one API call to another by the MegaMax server. The user’s credentials therefore must be supplied with every call to the API.
You will be running a JavaServer Faces application on GlassFish, locally, and it will be interacting with the MegaMax API provided by their OpenStack server. Therefore, there are two servers involved in this question: the local GlassFish server, and the remote API server. The motivation for this is to allow you to maintain user state – including the user’s credentials – on the GlassFish server, which then allows a simpler interaction with the MegaMax API. In particular, the user only needs to supply their credentials once, and the application can then send them with each API call.
Overview of provided code
Open the provided NetBeans project EMAP1 and explore it, noting the following points.
Under Source Packages:
1. In the beans package are two examples of JavaBeans, which provide the model part of the MVC application. CredentialsBean stores the name (oucu) and password of the user, and OrderBean will be used to maintain widget order information. Objects of bean classes are created for us automatically on the GlassFish server when the application is deployed.
2. The CredentialsBean class has the annotations @Named and @SessionScoped. The first indicates that you can access the automatically created bean object from a servlet using the name credentialsBean (note the initial lower-case letter), and the second indicates that the lifetime of this bean is an HTTP session. The method widgetsGet() uses the instance variables of the credentials bean (name and pwd) to call the MegaMax API.
3. In the rest package are Java RESTful client classes. Objects of these classes are constructed to call the MegaMax API. For example, in CredentialsBean, the method widgetsGet() calls the MegaMax API GET method for the widgets resource, using the method get_application_json(). The arguments to this method are the expected response type’s class (String.class) and the user’s credentials.
4. The class Utilities in the util package includes various methods to process JSON, including the method getAsJsonObject, which converts a JSON String to a JsonObject. The method prettyWidgets() is used by widgetsGet() to format the JsonArray part of the API response, using HTML table mark-up.
Under Web Pages:
1. credentialsForm.xhtml provides a form for a user to enter their credentials.
· The tags are a mixture of ordinary HTML and Facelet tags. The Facelet tags we are using have their own namespace, prefixed h:. Facelet tags are much the same as HTML tags in structure, but they are processed by the Faces Servlet and converted into HTML at runtime.
· Note how you can interact with the state of the credentialsBean. For example, the expression value=#{credentialsBean.name} sets the name instance variable of the bean when the Submit button is pressed, using the value the user entered in the inputText field.
· The action attribute of the commandButton refers to options. The local server automatically searches for this page to process the submitted form by appending the extension .xhtml.
2. options.xhtml presents links to pages allowing interactions with the MegaMax API.
3. widgetsGet.xhtml illustrates how the application can access the state of the credentials bean and also how it can call the bean’s methods widgetsGet() and computeColour(). The responses from the methods are inserted into the web page before it is displayed, and this allows us to apply a custom colour to the user’s name and show them a table of the widgets available to them.
The Java classes OrderBean and Utilities, and the web page orderForm.xhtml, are incomplete. None of the other files require changes.
Coding a web interface
To start coding your web interface, follow these steps:
a. Run the provided project and submit your personal credentials on the opening web page. You will then be presented with a web page entitled “MegaMax API Options” which has four links. The first link, for example, is used to to view the available widgets. Before moving on, you should click this link to explore the list of widgets (Figure 2).
Your personal credentials are available on the OpenStack server.
Start of Figure
End of Figure
Figure 2 Widgets list displayed by running the Netbeans project
a. The package rest includes the example Java RESTful clients Widgets.java and Orders.java. Next you need to generate a similar class to use some of the orders-related resources in the MegaMax API.
i. First you will need to register the MegaMax web service in NetBeans. There is a Web Application Description Language (WADL) file EMA_API.wadl included in the EMA download, which describes the MegaMax API.
Register this API within Netbeans, as follows:
In the Services window, expand the Web Services node, then right-click on it and click Add Web Service….
In the ‘Add Web Service’ dialogue box, select ‘Local File’.
Click Browse…, and navigate to where you saved the WADL file. Select it and click Open.
Click OK to exit the dialogue box.
The MegaMax API web service should now be registered in NetBeans as EMA_API in the Services window.
ii. Return to the Projects window. In the provided Java project, right-click on the Source Packages rest package in the Projects window. Select New > RESTful Java Client… to open the ‘New RESTful Java Client’ dialogue box (Figure 3).
Start of Figure
Figure 3 The new RESTful Java Client dialogue
End of Figure
Enter the ‘Class Name’ OrderItems, select the REST resource as ‘IDE Registered’, and click Browse… to select the order_items node in the MegaMax API under EMA_API (Figure 4).
Start of Figure
Figure 4 Selecting the orders node in the MegaMax API
End of Figure
Click OK to select the order_items resource and then click Finish to generate the OrderItems class in the package rest. You should now have a new file called OrderItems.java in your package.
b. (2 marks)
c. To allow a user to make an order, the page orderForm.xhtml needs to be completed. The page contains two incomplete forms to interact with the model backing bean, OrderBean. Complete the two forms on the orderForm page, using credentialsForm to guide you.
i. For the first form, you need to have a single input element for the client ID. Use it to set the OrderBean clientId attribute.
The API allows you to set the latitude and longitude at which an order was made. However, we will not be using these parameters in this web application, so we have just set them to 0 in the bean.
ii. For the second fieldset, you need to have inputs for the order id, widget id, number of widgets to order, and the price in pence per unit. Use the inputs to set the corresponding attributes of the OrderBean.
You will not be able to make an order yet, as you have not written the code that calls the API.
In your Solution Document, include a plain text copy of the HTML for the two forms in orderForm.
d. (3 marks)
e. The Submit button for the first form on the orderForm page directs the application flow to orderPost.xhtml, while the second form directs the flow to orderItemsPost.xhtml. These two ‘post’ pages are used to submit orders and order items respectively.
Open the orderPost.xhtml page and note the call to the orderPost method:
Start of Computer Display
value="#{orderBean.orderPost(credentialsBean.name, credentialsBean.pwd)}"
End of Computer Display
And on the orderItemsPost.xhtml page:
Start of Computer Display
value="#{orderBean.orderItemsPost(credentialsBean.name, credentialsBean.pwd)}
End of Computer Display
These two web pages rely on methods in the OrderBean class to call the POST operations provided by the MegaMax API.
The OrderBean methods in turn rely on the RESTful client classes Orders and OrderItems to perform the communication with the MegaMax server.
Take a moment to look at the classes Orders and OrderItems. In NetBeans ensure that the file Orders.java is visible in the editor window and pay particular attention to the Navigator pane (Figure 5)
Start of Figure
Figure 5 Methods in the Orders class
End of Figure
The class Orders includes a constructor, a close() method, a helper method to encode query or form parameters, and methods corresponding to GET and POST operations for the REST resource. View the BASE_URI by double-clicking on it in the Navigator pane. It represents the base URI that will be visited when using this RESTful client:
Start of Computer Display
String BASE_URI = "http://137.108.92.9/openstack/api/";
End of Computer Display
Note that the Orders constructor adds the string "orders" to the end of this URI. So constructing an object of the Orders class prepares you to access the orders resource of the REST API.
When you begin this assignment, there are no orders registered for your username. To check this, you can use a REST client such as a browser plugin (you may have used one for TMA 03)
RESTClient add-on for Firefox: https://addons.mozilla.org/en-GB/firefox/addon/restclient/
Advanced REST Client for Chrome: https://install.advancedrestclient.com/#/install
or an application such as PostMan (https://www.getpostman.com/apps), but for a simple GET operation you can use a browser and construct a URL with paramters. You can test this by visiting the orders resource in a browser and providing your username and password as query parameters:
Start of Computer Display
http://137.108.92.9/openstack/api/orders?OUCU=yourname&password=yourpassword
End of Computer Display
You will see a fail status along with the reason "404 - No Matching records", which is as you should expect.
Adding an order requires two interactions with the REST API. First, an order needs to be added for an existing client, and then items need to be added to the client’s order. You will provide code to complete these steps in the following parts.
i. Complete the OrderBean method orderPost() so that it constructs an Orders client object and calls its POST method, post_application_x_www_form_urlencoded().
The first argument to this method is String.class, because we want a string response from this method. The remaining arguments are the oucu and password (from the method parameters), followed by the client id, latitude and longitude (from the bean’s state).
The method should return the response from the MegaMax API – i.e. the value returned by the post method.
Copy and paste the code for your method to your Solution Document.
(3 marks)
ii. Create a new order by visiting the orderForm page and providing a valid client ID. For testing purposes, MegaMax have only two registered clients at the moment. Their IDs are 1 and 2.
When you press Submit, your completed orderPost method from part (i) should return a successful JSON response from the MegaMax server, which will be included in the orderPost page.
Copy the formatted JSON output to your Solution Document.
(2 marks)
f. Next, complete the code to add items to an order.
i. Complete the OrderBean method orderItemsPost so that it constructs an OrderItems client and calls its POST method.
The first argument to this method is String.class, because we want a string response from this method. The remaining arguments are the oucu and password (from the method parameters), followed by the order id, widget id, number of widgets to order and pence price (from the bean’s state).
The method should return the response from the MegaMax API – i.e. the value returned by the post method.
Copy and paste the code for your method to your Solution Document.
(3 marks)
ii. Add items to an existing order by visiting the orderForm page and completing the second form. Provide a valid order id (for example, from an order that you created earlier) and complete the other input fields.
When you press Submit, your completed orderItemsPost method should return a successful JSON response from the MegaMax server.
Copy the formatted JSON output to your Solution Document.
(2 marks)
g. In this part you need to complete the code that produces HTML tables of order items, which will be included in the orderPost and ordersGet web pages.
There are example methods to guide you in completing this part:
· CredentialsBean method widgetsGet(), which uses Utilities prettyWidgets()
· OrderBean method ordersGet(), which uses Utilities prettyOrders().
ii. In the class OrderBean, complete the method orderItemsGet(), to get order items from the MegaMax API.
We suggest that you begin by simply returning the JSON response from the MegaMax server, rather than trying to format it using prettyOrderItems() at this stage.
iii. In the class Utilities, create the method prettyOrderItems() to return an HTML table from an array of order items.
Now complete orderItemsGet() so that it calls this method.
Test your code by visiting the ‘View orders’ (ordersGet) page. (You can also test the code by creating a new order or order items using the orderForm.)
Copy your final versions of the methods orderItemsGet() and prettyOrderItems() to your Solution Document.
Include a screenshot of your ‘View orders’ page in your Solution Document, to show that you have been able to format the order items.
(5 marks)
Tips and troubleshooting
1. There are only two valid clients of MegaMax in the prototype API.
Visit the clients resource at the MegaMax REST service and supply your OUCU and password as query parameters to see that the existing clients are 1 and 2.
You cannot add new clients by supplying different client IDs. Only MegaMax administrators can do this operation at this time.
2. If you are having problems receiving or formatting tables from MegaMax in your NetBeans application, bear in mind that you can test success in creating an order by visiting
Start of Computer Display
http://137.108.92.9/openstack/api/orders?OUCU=yourname&password=password
End of Computer Display
To see order items, you can visit
Start of Computer Display
http://137.108.92.9/openstack/api/order_items?OUCU=yourname&password=password
End of Computer Display
3. Check the GlassFish server console for output from any print statements in the Java code. This can be found in the Output window. If this is not visible, select the menu option Window > Output. You can right-click on the server console and select Clear to make it easier to see recent messages.
4. You can refresh your view of a deployed application in Chrome by pressing Ctrl+Shift+R.
5. If Chrome reports ‘no active contexts’, close Chrome and re-run the application.
6. Be aware that refreshing a page that uses a POST operation will lead to another call to the MegaMax API, which may mean an extra order or order items being added.
Part 2 Mobile web app
To complete this question you are expected to develop, test and document a Cordova app for the Android platform.
Background
The MegaMax travelling sales staff have a requirement for a mobile app which has already been given the name ‘MegaMax Sale’ to present product information to potential clients. The information is to include product descriptions, product pictures, and the standard asking price. Through negotiation, sales staff are allowed to give clients a discount for larger orders or for widgets that are being promoted.
Once an order has been compiled and the prices have been agreed, the sales staff can then send in the order to the company. The cost of the order has to include VAT. The order information together with the time and the location of the sale will be sent to MegaMax to be added to their records. A salesperson can review their journeys by reviewing the places where an order was made.
Since MegaMax salespersons bring their own smart mobile devices, some of them running iOS (e.g. iPhones, iPads), some of them running Android (e.g. Samsung, Google Nexus), the mobile app should be developed using Apache Cordova. For the purposes of developing a demonstration prototype, we assume that most of them use Android devices; therefore, you are only required to test the mobile app on the Android platform.
For your development work you may use any text editor and the Cordova command line tools. Remember that you only need to submit the www folder, which will be the same regardless of which development option you have chosen.
Part 2(a)
Provide a set of three requirements (or functionalities) for this app that you might achieve in developing a prototype (the later exercise), and describe at least one obstacle for each that you foresee which may cause some difficulty for successfully achieving these requirements. Note that the obstacle could be non-technical, for example one from a business perspective. The obstacle that you describe should be different for each functionality.
(10 marks)
Part 2(b)
You can develop the mobile app by first creating an HTML mock-up of the interface with suitable elements (buttons, fields, etc.) and layout, and then later (Question 2(c)) implementing the logic to enable the app to perform the required actions. The interface should be of a form that allows the following actions:
1. Identify the salesperson by their OUCU and the client by a valid client id found in the clients table. As all calls to the API also require a password, this can be hard written into the code.
2. Navigate (with Prev Widget and Next Widget buttons) and display widget images, in addition to the description and asking price.
3. Add the current widget to ordered items, including the amount, and the agreed price.
4. Display the subtotal, the VAT, and the total of an order, together with the client’s name, address (latitude, longitude), and the timestamp of the order.
5. When pressing Place New Order, display a map centered around the location of the salesperson. The map should use markers to show the places where orders were placed by the salesperson.
A template HTML file (index.html) is provided for you. You can download this file from the module website. This file can be used as a starting point for your work. Implement the missing parts of the project associated with the form at the places indicated by comments. Make sure that you include appropriate links (event handlers such as ‘onclick’), from HTML elements which will invoke the JavaScript logic that you code later.
An example of the mock-up of the interface is shown below.
Start of Figure
Figure 6 Screenshot of an example mocked-up interface
End of Figure
My mockup has a scrolling action to display the actual order items that have been added to the order so far (Figure 7). When all the items (widgets) have been added to the order, the ‘Place new order’ button is used, and the map location of the client is looked up using the API and then added (latitude and longitude) to the order which can then be recorded using the API. At the same time, a map with the location shown with a pin is displayed.
I am intending to use the ‘Place new order’ button also to start a new (i.e. empty) order once one has been completed and saved using this button. When this button is pressed to create a new empty order, I will also change the map to show the route between the orders that the salesperson has placed today.
I have also allowed navigation of the widget catalogue and of the existing orders with ‘Next’ and ‘Prev’ buttons for these.
Note that you can use additional buttons and screens as you wish.
As an example of my approach to the app, two screenshots of a solution are shown below in Figure 7. Your solution can be different as long as it satisfies the functional requirements.
Start of Figure
Figure 7 Screenshots of an example solution
End of Figure
(10 marks)
Part 2(c)
As described earlier, a REST API has been prepared to facilitate the management of MegaMax Sales, so that you do not have to worry about the storage of data. What you need to do is to make use of the API URLs explained in the "EMA Database and API" guide, to implement the required functionalities. Before diving into the functional requirements read the database and API guide and then return here to look at the examples of API calls below.
Start of Table
RESTful services (responses are in JSON format)
|
Service endpoints and example responses |
GET |
POST |
DELETE |
|
http://137.108.92.9/openstack/api/widgets?OUCU=user1&password=password {"status" : "success", "data" : [{"id":"8", "url":"http:\/\/137.108.92.9\/openstack\/images\/widget1.jpg", "pence_price":"10", "description":"General Purpose Threaded Coach Bolt Bright Zinc-Plated M10 x 180mm"}, {"id":"9", "url":"http:\/\/137.108.92.9\/openstack\/images\/widget2.jpg", "pence_price":"12", "description":"Coach Screw 10 x 50mm"}] } {"status" : "error", "message" : " 401 - invalid username or password"} |
On "success", returns the widget id, image url, price and description; otherwise returns "error". |
N/A |
N/A |
|
http://137.108.92.9/openstack/api/orders?OUCU=user1&password=password {"status" : "success", "data" : [{"id":"6", "client_id":"2", "date":"2017-01-05 00:00:00", "latitude":"99.00000000", "longitude":0}, {"id":"8", "client_id":"1", "date":"0000-00-00 00:00:00", "latitude":0, "longitude":"-20.00000000"}] } {"status" : "fail", "data" : [{"reason":"No matching records"}] } |
Returns all the orders placed by the user with the given OUCU with the order id, "client_id", date and location on "success"; otherwise, returns a message why it has "failed". Note that when the order was created without specifying the value of latitude or longitude, they may be stored as "null" instead of floating point number. To avoid this problem, you can simply make sure to only create orders with actual values for latitude and longitude, e.g., 0 and 0. |
Insert an order with corresponding fields such as {client_id, date, location}. |
On deletion, the order will be marked as not confirmed. |
|
http://137.108.92.9/openstack/api/order_items?OUCU=user1&password=password {"status" : "success", "data" : [{"id":"10", "order_id":"6", "widget_id":"3", "number":"12", "pence_price":"45"}, {"id":"2", "order_id":"6", "widget_id":"4", "number":"10", "pence_price":"111"},{"id":"8", "order_id":"10", "widget_id":"45", "number":"1001", "pence_price":"599"}] } {"status" : "fail", "data" : [{"reason":"No matching records"}] } |
On "success", returns the matched order items, where "order_id" refers to the order’s id, "widget_id" refers to the widget’s id, "number" refers to the number of items and "pence_price" refers to the agreed price. On "fail", no matching records are shown. |
On success, create a new order_item if the widget has not been added, otherwise the order_item will be added to the order. |
|
|
http://137.108.92.9/openstack/api/clients?OUCU=user1&password=password {"status" : "success", "data" : [{"id":"7", "name":"fred bloggs", "address":"45, something road", "phone":"01234 567 89", "email":"[email protected]"}, {"id":"8", "name":"Fred Bloggs", "address":"55, something road", "phone":"01234 567 89", "email":"[email protected]"}, {"id":"9", "name":"Fredina Bloggs", "address":"45, something road", "phone":"01234 567 89", "email":"[email protected]"}] } |
Returns the detailed id, name, address, phone and email of a client. |
Add a client, where the address will be updated by the GPS location. |
N/A |
End of Table
The call listed below is to an API called Nominatim (http://nominatim.openstreetmap.org/). This mapping application can be used to generate detailed information on the location of a client. In general a call should have the form:
http://nominatim.openstreetmap.org/search/<ADDRESS>?format=json&countrycodes=gb
Given the <ADDRESS> this returns the detailed address information, including the latitude as "lat" and longitude as "lon" attributes:.
[{"place_id":"96368024", "licence":"Data © OpenStreetMap contributors, ODbL 1.0. http:\/\/www.openstreetmap.org\/copyright", "osm_type":"way", "osm_id":"141734330", "boundingbox":["54.5963713", "54.5965609", "-5.9236627", "-5.9233236"], "lat":"54.59646635", "lon":"-5.92349534474763", "display_name":"Open University, May Street, Town Parks, Belfast, County Antrim, Northern Ireland, BT1 3JL, United Kingdom", "class":"building", "type":"yes", "importance":0.201},…]
So, for example, the address of the client with id of ‘1’ in the clients table is given as "555 Silbury Blvd, Milton Keynes MK9 3HL". Using this address in a URL, the Nominatim application will return a JSON structure with more information. So the call
Start of Computer Display
http://nominatim.openstreetmap.org/search/"555 Silbury Blvd, Milton Keynes MK9 3HL"?format=json&countrycodes=gb
End of Computer Display
returns the structure:
Start of Computer Display
[ { "place_id":"71155256", "licence":"Data © OpenStreetMap contributors, ODbL 1.0. http:\/\/www.openstreetmap.org\/copyright", "osm_type":"way", "osm_id":"32144305", "boundingbox":["52.0441649","52.0445506","-0.7567538","-0.7558532"], "lat":"52.0445506", "lon":"-0.7558532", "display_name":"Silbury Boulevard, Central Milton Keynes, Milton Keynes, South East, England, MK9 3AG, United Kingdom", "class":"highway", "type":"unclassified", "importance":0.5 } ]
End of Computer Display
You can find out more about Nominatim at http://wiki.openstreetmap.org/wiki/Nominatim.
In the other API calls in the table, 137.108.92.9 is a server at the Open University preconfigured using an OpenStack instance.
The Functional Requirements (FR) for this app are as follows:
· FR1 The app should make an order as if the salesperson is at a client site with a valid OUCU and password for the salesperson and the client id:
· FR1.1 Validating the OUCU starts with a letter and ends with a number.
· FR1.2 Navigating the widgets catalogue (with Previous and Next buttons) and display of widget images, in addition to the description and asking price.
· FR1.3 Adding the currently displayed widget to the order items, including the amount and the agreed price.
· FR1.4 Displaying the sum of ordered items and adding VAT to the agreed price of each of the order items at 20%.
(12 marks)
· FR2 For the salesperson to review their performance:
· FR2.1 Displaying a Map for the area around the current location of the salesperson when at the client's premises and placing or viewing an order.
· FR2.2 When clicking on Place NEW Order to start an empty order, displaying the orders along the day’s journey with markers, where the location of client’s addresses are used to place the markers.
(8 marks)
Once you have completed your implementation you should produce a guide, which covers:
1. The functionality you have implemented (what the app does). You may well wish to include some screenshots of the app. This should be written with the end user in mind.
2. Instructions on installing and configuring the additional plugins that you have used. This description should be sufficient for a third party to take your source code and reproduce your application.
The maximum word count for your report for this question is 500 words. This count includes titles and figure captions. There are no penalties for exceeding the limit, but any words in excess of 500 will not be marked.
There are no marks allocated to the report itself but the report is required to gain the marks allocated to the other parts of the question. By documenting the functionality of the app (and any limitations, etc.) and how to run your app, you are assisting the marker in evaluating and testing your app.
Part 3 Developing the apps
Given the REST API and its potential to support applications such as those you have developed, how can the company go forward? The company has decided to invest in some new systems and technology, and has identified a set of issues that it believes are central to developing a better solution in the medium term. These are:
1. dealing with legal issues and security risks. The company will be storing data about clients such as contact details, bank details and transaction records, as well as stock and order details.
2. providing appropriate storage with backup and security for this, and maintaining the accuracy and consistency of data across applications
3. potential costs and savings of implementing or using new technology, staffing, training, licensing etc.
4. requirements for personnel and their skills for development, maintenance and use of the system and applications
5. potential for and approaches to scaling and supporting greater reliability of the applications.
In the first section of your report, you should outline a set of technology options and components that the company might employ to take advantage of cloud and mobile technology within their operations. Be sure to make a clear and justified recommendation for adopting your selections. Your choice of technology should describe a set of components (web server, networks, software etc) in concrete terms and not discuss, for example, the different levels of approach possible (IaaS, SaaS etc). Note that MegaMax currently has both a central IT facility and travelling salesteam with other requirements. It is advisable to include a diagram of the elements you include with clear labelling.
Then select three of the items from the list above and discuss them and how they impact MegaMax in the context of your recommendation. In your report you should have four clear sections, one for the set of technology options and then one for each item from the list. Use a range of references as a foundation for your discussion. You should search for quality information sources online, including via the OU Library.
It is important not to cover areas in general terms but to be specific to MegaMax and the development of the two applications (web and mobile) that have been prototyped, and to consider the potential uses of cloud technology. You will not gain marks for covering more than three of the issues.
Relate your discussion to MegaMax as much as possible. Do not repeat the descripton of MegaMax and you are not required here to write a structured report with an introduction etc but you should have four clear sections and a set of references that you have used.
The maximum word count for this question is 2000 words. This count includes titles and figure captions but not references. There are no penalties for exceeding the limit, but any words in excess of 2000 will not be marked.
(40 marks)
Page 1 of 3 2nd August 2019
ema_database_and_api.doc
EMA Database and API
TM352 Web, mobile and cloud technologies
EMA Database and API
Copyright © 2019 The Open University
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, transmitted or utilised in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without written permission from the publisher.
WEB 058254-2
3.1
Contents
· The order_items database table
· widgets API and widget images
Introduction
This document provides an overview and details of the EMA database, its content and the API with which it can be accessed.
EMA Database and API
Throughout this document the URL for the API has an IP address of:
Start of Computer Display
137.108.92.9
End of Computer Display
If it is necessary for the module team to change this IP address, the new IP address will be publicised in the TM352 EMA forum. Check the forum if calls to the API fail or before starting work on this EMA.
The database
The prototype database has a simple set of four tables which represent the core data that the company employs to support both web sales and the sales team. The tables are:
· clients
· orders
· order_items
· widgets
Each table is described in a section below. You will not interact with the database directly, but will use the REST API to access and store data. So the database details are intended only to provide you with some idea of the nature of the data and how the API functions. The REST API is described after the database description.
The clients database table
The clients table represents the company’s clients. Each row of the table describes a client in terms of their name, address, phone number and email address. A client is uniquely identified by an identifying number or ‘id’.
The table has five columns, which are listed below with their types.
Start of Computer Display
id int(11) /* an integer field, up to 11 digits long name char(30) /* a character field, 30 characters long address char(100) phone char(12) email char(25)
End of Computer Display
The clients table has some sample data in place, which is listed below. You should not attempt to alter, delete or add to this particular table.
Start of Table
|
id |
name |
address |
phone |
|
|
1 |
Royal Mail Group Ltd. |
Brudenell Dr, Brinklow, Milton Keynes MK10 0BS |
01908 285025 | |
|
2 |
Costco Wholesale UK Ltd. |
Mandeville Dr, Kingston, Milton Keynes MK10 0DB |
0345 602 102 |
End of Table
You should use this data when you add any new data to other tables. So, for example, if you add a new record to the orders table, then the order you create contains the id of the client that the widgets are for. So you should use a valid id from the clients table above (one of ‘1013’ or ‘1014’). Your copy of the clients table may have differing id values.
The orders database table
Each row of the orders table represents an order. The table has five columns, which are listed below with their types.
Start of Computer Display
id int(11) /* unique identifier of this order client_id int(11) /* an ID from the clients table date datetime /* date and time the order was placed latitude decimal(10,8) /* latitude of sale location longitude decimal(11,8) /* longitude of sale location
End of Computer Display
The id is a unique number which is of type auto_increment so that it is assigned by the system as a unique number when a row is added to the table. So in creating a new order record you need to provide a client id from the clients table, a date and a latitude and longitude, which specify the time and place the order was made.
A latitude can range from −90 to +90 degrees and a longitude can range from −180 to +180 degrees.
It is expected that a mobile app would provide location data, but that orders from the website will not and will use ‘0’ values instead. This location (latitude 0, longitude 0) is not a valid location for any client. An example of the data that can be found in the table is shown below.
Start of Table
|
id |
client_id |
date |
latitude |
longitude |
|
10 |
1 |
2017-01-05 14:27:02 |
0 |
0 |
|
11 |
2 |
2017-01-04 16:30:00 |
40.41677500 |
-3.70379000 |
|
12 |
2 |
2017-02-02 17:32:02 |
51.50735100 |
-0.12775800 |
|
14 |
1 |
2017- |
52.04062200 |
-0.75941700 |
End of Table
Note that the actual widgets in an order are not listed in the orders table. Instead, the id from the orders table is used to create a set of one or more ‘order items’ in another table which is described next.
The order_items database table
The order_items table has five columns, listed below.
Start of Computer Display
id int(11) /* unique identifier of this order item order_id int(11) /* an id from the order table widget_id int(11) /* unique id of a widget from widgets table number int(11) /* number of the widget ordered pence_price int(11) /* price per widget in pence
End of Computer Display
There can be multiple order_items that have the same order_id, which together make up the items of the order. The order_item id field is automatically generated by the system when a new record is created.
Below is an example of data that might be found in this table.
Start of Table
|
id |
order_id |
widget_id |
number |
pence_price |
|
100 |
10 |
6 |
100 |
10 |
|
101 |
10 |
8 |
25 |
12 |
|
102 |
11 |
2 |
1000 |
8 |
|
104 |
14 |
9 |
200 |
15 |
End of Table
The widgets database table
In the widgets table each row describes a unique widget product. The columns in the widget table are listed below.
Start of Computer Display
id int(11) /* unique identifier of this widget url varchar(300) /* URL of an image of the widget description varchar(300) /* text description of the widget pence_price int(11) /* price per widget in pence
End of Computer Display
The widgets table is a small catalogue of sample widgets and contains the data shown below.
You should not attempt to alter or add to this particular table. The actual values in the table are shown below.
Start of Table
|
id |
url |
description |
pence_price |
|
1 |
http://137.108.92.9/openstack/images/widget1.jpg |
Brass Self-Tapping Wood Screw 20mm |
10 |
|
2 |
http://137.108.92.9/openstack/images/widget2.jpg |
Coach Screw 10 x 50mm |
12 |
|
3 |
http://137.108.92.9/openstack/images/widget3.jpg |
Rawwlplug LX Masonry Bolts 12x140mm |
13 |
|
4 |
http://137.108.92.9/openstack/images/widget4.jpg |
Marine Eye Bolt 6 x 40mm |
8 |
|
5 |
http://137.108.92.9/openstack/images/widget5.jpg |
Exterior Coach Screw Organic Green M10 x 160mm |
6 |
|
6 |
http://137.108.92.9/openstack/images/widget6.jpg |
Marine Eye Bolt 8 x 100mm |
14 |
|
7 |
http://137.108.92.9/openstack/images/widget7.jpg |
Socket Button Screw A2 stainless Steel M6 x 20mm |
12 |
|
8 |
http://137.108.92.9/openstack/images/widget8.jpg |
Roofing Bolt Bright Zinc-Plated M6 x 30mm |
5 |
|
9 |
http://137.108.92.9/openstack/images/widget9.jpg |
Zinc-Plated High Tensile Steel Hex Bolt M10 x 120mm |
9 |
|
10 |
http://137.108.92.9/openstack/images/widget10.jpg |
Concrete Bolt 10 x 100mm |
12 |
End of Table
The JPEG images have a standard square aspect ratio of 330 × 330 pixels. Widgets 6, 8 and 10 are 96 dpi rather than 72 dpi, but appear to have the same size in a browser.
Table relationships
The tables are related as shown in Figure 1. All the tables have a unique primary key (PK) which is generated by the system. The clients table key is also used to index orders as the value of client_id so that it is efficient and simple, given a client ID, to retrieve the set of orders belonging to the client.
Start of Figure
Figure 1 Table keys and relationships
End of Figure
The orders id key is also used to index order_items so that items making up any particular order can be retrieved. The widgets id is also used in order_items so that it is possible to find, for example, the number of a particular widget that is on order.
The REST API
The database sits behind a REST API coded in PHP. This allows access to the database tables in terms of saving or retrieving data for presentation.
In general, REST HTTP operations are used to access data as outlined in the table below.
Start of Table
|
HTTP operation |
Action |
|
GET |
Read record(s) and return these |
|
POST |
Create a new record |
|
PUT |
Update a record |
|
DELETE |
Delete an existing record |
End of Table
Each database table has a corresponding URL as part of the API, which is used to access the table:
Start of Table
|
Database table |
Base URL |
|
clients |
http://137.108.92.9/openstack/api/clients |
|
orders |
http://137.108.92.9/openstack/api/orders |
|
order_items |
http://137.108.92.9/openstack/api/order_items |
|
widgets |
http://137.108.92.9/openstack/api/widgets |
End of Table
In calling the API, each base URL should be extended with parameters such as database authorisation (OUCU and password) and items of data. Guidance on parameters is given later in the sections on the API.
Each operation can be performed on any table via the API, but not all operations make good sense on all tables; attempting an operation that is inappropriate will result in an error being returned. Some operations require that you send some data to the API. So, for example, to delete a record would require passing in a unique ID for the record so that the required record can be identified and deleted. All records in the database tables have a unique identifying ID item in a column called ‘id’.
In general, for each API interface to a table (clients, orders, order_items and widgets) there are two operations that can be performed without an ID being supplied:
· A GET with no ID simply gets all records from the table. Values for any of the data found in the record can be specified, in which case only records matching the data values will be returned.
· A POST has to be performed with no ID as it generates a new record (using the data you supply), but the system will generate the unique ID for the record itself.
And, in general, there are three operations that should be supplied with an ID to identify a single record in the database for the operation:
· A GET with an ID will retrieve the single record with that ID rather than all records.
· A PUT with an ID will update the record identified by the ID provided with the other data provided in the call to the API.
· A DELETE with an ID will remove the record identified by the ID provided.
Note that if you provide an ID that does not exist an error will be returned (see the section on errors later in the document).
The operations appropriate for each table, the data that needs to be passed to the API, the result (data or a message or a record) sent back by the API, and error conditions and messages are described in the following sections.
First we will examine the need to pass in some credentials when calling the API.
Authorisation
Each call to the API requires that you provide your OUCU and your OpenStack password as parameters on the URL call to the API. The API is not connected to your OpenStack account or to the Horizon dashboard, but the password is reused for the API. You can find your password on your OpenStack home page at http://students.open.ac.uk/mct/tm352/openstack/.
So you should pass your OUCU and OpenStack password as parameters on every call to the API. As usual with a REST API, no user state is maintained from one API call to another by the MegaMax server. Therefore the user’s credentials must be supplied with every call to the API as additional parameters on the URL sent to the API server. Examples of how to do this are given later.
clients API
The clients table is read-only so only the GET operation to retrieve record(s) is permitted. There are two different ways to make a GET request:
1. With a valid client id value appended to the end of the URL itself, before any additional parameters. If an id is provided then the API will return the single client record that has that id value. If my OUCU is ‘tm352’ and my OpenStack password is ‘6WGc5Q76’, then the GET request for the record describing the client with id 7 would have the form:
Start of Computer Display
http://137.108.92.9/openstack/api/clients/7?OUCU=tm352&password=6WGc5Q76
End of Computer Display
2. With no client id. In this case, the API will return all the client records from the database. Other data can be specified on the GET so that only matching records are returned.
So the API URL for GET has an optional id and the general form:
Start of Computer Display
http://137.108.92.9/openstack/api/clients/{id}?OUCU=oucu&password=password
End of Computer Display
where id is the optional id, oucu is your OUCU, and password is a valid password.
As an example, consider the GET request below. Here the student’s OUCU is ‘fhs134’ and the OpenStack password is ‘6WGc5Q75’. The request is for the record of the client with id of ‘1’:
Start of Computer Display
http://137.108.92.9/openstack/api/clients/1?OUCU=fhs134&password=6WGc5Q75
End of Computer Display
The API returns a JSON structure:
Start of Computer Display
{ "status" : "success", "data" : [ { "id":"1", "name":"Widgets Galore", "address":"555 Silbury Blvd, Milton Keynes MK9 3HL", "phone":"0123 456 789", "email":[email protected] } ] }
End of Computer Display
If an ID is provided that does not exist then an error is returned (see the section on errors later).
widgets API and widget images
The widgets table is also read-only so again the only applicable operations are a GET, either with a widget id to retrieve a specific widget record, or with no id to retrieve all widget records.
Recall that each widget has an image that is hosted on a web server running on the same machine as the API code. How to form the URL for any widget image is described in the earlier section on the widgets database table.
The API for GET has the general form (with optional id etc. as for the clients table):
Start of Computer Display
http://137.108.92.9/openstack/api/widgets/{id}?OUCU=oucu&password=password
End of Computer Display
As an example, this GET
Start of Computer Display
http://137.108.92.9/openstack/api/widgets/8?OUCU=tm352&password=6WGc5Q76
End of Computer Display
will return the details of the widget with ID of ‘8’:
Start of Computer Display
{ "status" : "success", "data" : [ { "id":"8", "url":"http:\/\/137.108.92.9\/ openstack\/images\/widget1.jpg", "pence_price":"10", "description":"General Purpose Threaded Coach Bolt Bright Zinc-Plated M10 x 180mm" } ] }
End of Computer Display
Note that in the JSON that is returned, the forward slashes in the URL are escaped (as is standard in MySQL; see https://dev.mysql.com/doc/refman/5.7/en/string-literals.html). Using JQuery you can obtain a string value using the parseJSON function, which can be used, for example, to set the src attribute for an image element.
Again, if the ID is invalid or if the password or OUCU used are incorrect then an error will be returned.
orders API
The orders table is writable so that it is possible to create and save new orders in an application. When creating a new order, the database will generate the ID value so this should not be passed to the API.
For the orders table it is possible to perform GET and POST operations.
GET
GET with no ID will retrieve all the orders. GET with an ID value will retrieve just the single record matching the ID. If an ID is provided and there is no matching record then an error is returned. A successful GET with an ID returns the record with that ID. For example, the GET request
Start of Computer Display
http://137.108.92.9/openstack/api/orders/53?OUCU=tm352&password=6WGc5Q76
End of Computer Display
will return the order record with an ID value of 53:
Start of Computer Display
{ "status" : "success", "data" : [ { "id":"53", "client_id":"1", "date":"2017-02-17 11:29:35", "latitude":null, "longitude":null } ] }
End of Computer Display
If an ID is provided and is not found then an error will be returned.
POST
POST will create a new record. The record should have appropriate values for the database fields (client_id, latitude and longitude) but no ID should be passed to the API because the database will generate a new unique ID value for the record. The value of client_id is validated against the clients table, and so must have a value for a client record that already exists, otherwise an error will be returned. The date value is provided by the system and so should not be passed to the API.
A POST
Start of Computer Display
http://137.108.92.9/openstack/api/orders
End of Computer Display
with additional body elements
Start of Computer Display
OUCU=tm352 password=6WGc5Q76 client_id=1 latitude=89 longitude=-20
End of Computer Display
can be sent to the API (perhaps using a POST form or a client tool) to return a success message and the new record, including the generated ID:
Start of Computer Display
{ "status" : "success", "data" : [ { "id":"59", "client_id":"1", "date":"2017-02-20 13:01:50", "latitude":"89.00000000", "longitude":"-20.00000000" } ] }
End of Computer Display
If the values are not appropriate for the database fields then an error will be returned.
PUT
PUT will update an existing record with new values. The request must include a valid order ID value to uniquely identify the existing record that is to be updated. To change the client_id to ‘2’ of an order with ID 53, a PUT request can be made to the API.
Start of Computer Display
http://137.108.92.9/openstack/api/orders/53
End of Computer Display
with body elements:
Start of Computer Display
OUCU=tm352 password=6WGc5Q76 client_id=2
End of Computer Display
The adjusted record is returned showing the new value(s) that were inserted into the record:
Start of Computer Display
{ "status" : "success", "data" : [ { "id":"53", "client_id":"2", "date":"2017-02-17 11:29:35", "latitude":null, "longitude":null } ] }
End of Computer Display
If the record does not exist or the values provided are not appropriate for the fields in the database then an error is returned.
DELETE
A DELETE will remove a single record from the database. The unique ID of the record must be provided. To DELETE an order with an ID value of 53, the following call can be made:
Start of Computer Display
http://137.108.92.9/openstack/api/orders/53
End of Computer Display
with elements:
Start of Computer Display
OUCU=tm352 password=6WGc5Q76
End of Computer Display
This will return a message:
Start of Computer Display
{"status" : "success"}
End of Computer Display
order_items API
An order_items record represents a part of an order. Each part of an order will be for a specific widget and a quantity of that widget at an agreed price.
Like the orders table, the order_items table is writable so that when an order is created records can also be added to this table for the widgets making up the order. As with the orders table, GET (retrieve all records) and POST (create a new record) can be performed with an ID for the order_items record, and GET (retrieve one specific record), PUT (update a specific record) and DELETE (remove a specific record) can be performed with an ID of a record.
To retrieve all the records belonging to an order with order_id 6 we can use the GET:
Start of Computer Display
http://137.108.92.9/openstack/api/order_items?OUCU=tm352&password=6WGc5Q76&order_id=6
End of Computer Display
which returns, for example, the two items (12 of widget 3 and 10 of widget 4):
Start of Computer Display
{ "status" : "success", "data" : [ { "id":"10", "order_id":"6", "widget_id":"3", "number":"12", "pence_price":"45" }, { "id":"2", "order_id":"6", "widget_id":"4", "number":"10", "pence_price":"111" } ] }
End of Computer Display
API error messages
There are three types of error message:
1. If the API call uses a URL where the URL path does not begin with openstack/api, e.g. http://137.108.92.9/incorrect/api/clients then the API will not return any JSON structure but will return an HTTP header with a 404 response. Note that applications are expected to generate valid URLs; therefore this error should not occur once you have a working application and so the application itself does not need to handle this type of error.
2. If the request type is not a valid HTTP verb (GET, PUT, POST or DELETE) then the API will not return any JSON but will return an HTTP header with a 405 response. As with the previous error message type, the application does not need to handle this type of error.
3. If the API call is invalid in some way, e.g. an incorrect table name, or the request does not contain the necessary parameters for the table operation in question, then the API will return a JSON structure that contains an error message. Various error messages and codes may be produced, but the JSON structures have a common format:
Start of Computer Display
{ "status" : "error", "message" : "Some string message" }
End of Computer Display
In this structure the string "Some string message" will vary according to the actual error encountered. The error message can be a string such as:
Start of Computer Display
" 500 - GET error MESSAGE"
End of Computer Display
where MESSAGE is the detailed reason from MySQL as to why the GET failed
Start of Computer Display
" 500 - Execute error MESSAGE"
End of Computer Display
where MESSAGE is the detailed reason from MySQL as to why the INSERT, UPDATE or DELETE failed
Start of Computer Display
" 500- Invalid table name for this action."
End of Computer Display
Start of Computer Display
" 401 - invalid username or password"
End of Computer Display
Start of Computer Display
" 400 - ID field missing"
End of Computer Display
Start of Computer Display
" 404 - No matching records"
End of Computer Display
Start of Computer Display
" 500 - foreign key error - client_id not found in clients table"
End of Computer Display
Start of Computer Display
" 500 - foreign key error - order_id not found in orders table"
End of Computer Display
Start of Computer Display
" 500 - foreign key error - widget_id not found in widgets table"
End of Computer Display
Start of Computer Display
" 500 - missing required field for operation"
End of Computer Display
If a GET is performed but no record is returned there is a different status in the error message:
Start of Computer Display
{ "status" : "fail", "reason": "404 - No matching records" }
End of Computer Display
In general the status can be:
· "success", when there has not been any error
· "fail", when the request is valid but doesn’t match any record or, in the case of adding an order_item, with an order ID that does not exist. Such errors do not indicate a problem with the calling client program: it is just that the operation fails because its meaning is incorrect.
· "error", when the request itself is incorrect. So, for example, if it is missing a critical field value, the value is not legal or if the login credentials are incorrect. This sort of error indicates that the calling client has constructed the request incorrectly in some way.
It is expected that usually an application will test the value of status and act accordingly. If the value of status is fail or error, then an application should print out an appropriate message to inform the user or developer of the nature of the error.
Page 1 of 3 2nd August 2019