webServices

  1. API's do
    • provide an interface
    • use SS to build web pages and web apps
    • heavy dependency on browser
    • Web Services provide data-builds things you can look at
  2. data format
    JSON
  3. Types of API's
    • REST API - url path to resource
    • Representation State Resource
    • SOAP is XML bases-allows remote procedure calls
    • Simple Object Access Protocol
  4. .htaccess
    • rewrite rules
    • primitive
    • easy to use and reflect structure of data to simplify building of client applications
    • maps uri into url?parameters
    • employees/Sales =>employees?dept=Sales
    • allows hiding to low level db table names
  5. A2 Routing Rules
    • define set of rules for PUT, POST, GET, DELETE
    • rewrite rules to match URI patterns(regex)
  6. ..../employees?page=5
    • left of ? = uri, identifies the resourse
    • right of ? = identifies parameters, additional filters/info
  7. status codes
    • 200 = ok
    • 201 = created
    • 404 = not found
  8. DELETE
    • in general don't delete a collection
    • only delete a single at a a time
  9. POST
    • create, don't specify id, get id back
    • POST requests are typically used to add new single resource instances to a collection.(create new resource)
    • POST requests do not have to define the entire resource.
    • eg curl -X POST .../public/employees -d “{\”first\”:\”Noel\”,\”last\” :\”Fielding\”}”
    • result = {“status”:201,”id”:“/employees/NEWID”}
  10. PUT
    PUT requests create or update a complete resource with id specified.

    • curl -X PUT .../public/employees/123 -d “{\”first\”:\”Noel\”,\”Fielding\” etc }”
    • Effect: Adds a new (or updates an existing ) employee. (I.e. configures and executes aMySQL insert statement).
    • Return value: {“status”:201},”id”:“/employees/123”} or {“status”:200,”id”:“/employees/123”}
    • Response code: 201 Created (or 200 Ok – if updated)
    • update whole resource even if some parts remain the same.
  11. paging metadata : “pager” object
    • "page_size”: fixed at 20,
    • “page_count”: total number of pages for requested collection,
    • “current_page_number”: defaults to page 1 if not specified,
    • “previous_page_number”:null if current page is 1,
    • “next_page_number”: null if current page =last page,
    • “current_page_path”:“/employees?page=10”,
    • “previous_page_path”:“/employees?page=9”,
    • “next_page_path”:“/employees?page=11”,
    • “last_page_path”:“/employees?page=15000
  12. paging metadata.
    The result should now consist of “status” and “pager” obejcts and a “data” array nested inside a single JSON-encoded result object.
  13. Allow API GET requests to specify an optional page number
    • For example the API request path is /employees?page=10 should map to a SELECT
    • statement with LIMIT=20 and OFFSET=(page#-1)*size.
  14. example uri's
    • URIs in the browser:
    • http://localhost:8000/public/departments
    • http://localhost:8000/public/departments/d005
    • http://localhost:8000/public/employees
    • http://localhost:8000/public/employees/12345
  15. GET regex
    http://localhost:8000/public/employees

    http://localhost:8000/public/employees/N

    http://localhost:8000/public/employees/M:N
    $app->get('/employees[/]',

    $app->get('/employees/{id:\d+}[/]',

    $app->get('/employees/{from:[0-9]+}:{to:[0-9]+}[/]',
  16. GET regex
    http://localhost:8000/public/employees/Sales

    http://localhost:8000/public/employees/Sales/M:N
    $app->get('/employees/{dept:[a-zA-Z-]+}[/]',

    $app->get('/employees/{dept:[a-zA-Z-]+}/{from:[0-9]+}:{to:[0-9]+}[/]',
  17. Implement Route Callback functions
    • Following the sample code in dbutils.php, define five functions that will be used by the five routing rules listed above. Each function should execute a PDO prepared statement (after binding any required parameters) and should return a JSON-encoded result.
    • Add code to employees.php to associate the above callback functions to the corresponding routing rules. (I.e. comment out the acknowledgement messages and replace them with the callback functions).
  18. REST vs CRUD
    • id is part of db
    • REST - id is not part of REST resource
    • CRUD - id is part of record
  19. regex
  20. A typical pattern to identify a number would look like this:
    [0-9]+
  21. URL rewriting can be one of the best and quickest ways to
    improve the usability and search friendliness of your site.
  22. .htaccess
    • # Turn on the rewriting engine
    • RewriteEngine On

    • # Handle requests for "pet-care"
    • RewriteRule ^pet-care/?$ pet_care_info_01_02_2008.php [NC,L]
    • #####
    • [NC,L] - "Flags", that tell Apache how to apply the
    • rule. In this case, we're using two flags. "NC", tells Apache that this
    • rule should be case-insensitive, and "L" tells Apache not to process any
    • more rules if this one is used.
  23. RewriteRule ^parrots/([A-Za-z0-9-]+)/?$ get_product_by_name.php?product_name=$1 [NC,L] # Process parrots
    With this rule, any URL that starts with "parrots" followed by a slash (parrots/), then one or more (+) of any combination of letters, numbers and hyphens ([A-Za-z0-9-]) (note the hyphen at the end of the selection of characters within square brackets - it must be added there to be treated literally rather than as a range separator). We reference the product name in brackets with $1 in the substitution.
  24. What is REST?
    REST is a set of principles that define how a server and client can communicate with each other (and external resources) in a simple, straightforward, and robust manner. Though you’ll often see the words “REST” and “architecture” together, REST is not a specific architecture.
  25. explain REpresentational in REST
    • REST stands for REpresentational State Transfer.
    • Representational refers to the fact that when you access something via the web what is returned to you is a representation of the object, not the actual object itself.
  26. explain State in REST
    State refers to the belief that no session state should be kept on the server. Each request from the client should contain all of the necessary information for the server to understand the context of a request without referencing a previous transaction. All state is maintained by the client.
  27. explain transfer in REST
    And Transfer refers to how data is shared across a network between clients and servers.
  28. Principles of REST
    • Identify Everything as a URI(uniform resource identifier)
    • Hypermedia as the Engine of Application State
    • Requests are Stateless
  29. Requests are Stateless
    • Central to REST is the idea of
    • statelessness. That is, each request handled by the server can be done without knowing anything about any previous request. Or to put it another way, the client supplies all necessary information in the request needed by the server to fulfill it.
  30. Standard Protocol Usage
    there is nothing in REST that requires it to use HTTP. And yet, most of the time when you see a REST system it is built on HTTP. The reason for that is that HTTP uses four basic operations (GET, PUT, POST, and DELETE) to do all operations, and REST gravitates towards a small, standardized set of operations.
  31. All route callbacks accept three parameters (the third one is optional):
    Request: this contains all the information about the incoming request, headers, variables, etc.

    Response: we can add output and headers to this and, once complete, it will be turned into the HTTP response that the client receives

    Arguments: the named placeholders from the URL (more on those in just a moment), this is optional and is usually omitted if there aren’t any
  32. how do you get id from
    $app->get('/ticket/{id}',
    • the route will take the portion of the URL from where the {id} is declared, and it becomes available as $args['id'] inside the callback.
    • $ticket_id = (int)$args['id'];
  33. It is possible to get all the query parameters from a request by doing
    $request->getQueryParams()

    • for the URL /tickets?sort=date&order=desc we’d get
    • ['sort' => 'date', 'order' => 'desc']
  34. When working with incoming data, we can find this in

    The POST request data can be found
    the body.

    The POST request data can be found in the body of the request
  35. a post sends two fields: “title” and “description”
    • $app->post('/ticket/new', function (Request $request, Response $response) {
    • $data = $request->getParsedBody();
    • $ticket_data = [];
    • $ticket_data['title'] = filter_var($data['title'], FILTER_SANITIZE_STRING);
    • $ticket_data['description'] = filter_var($data['description'], FILTER_SANITIZE_STRING);
    • // ...
  36. sql for
    $app->get('/employees/{dept:[a-zA-Z-]+}/{from:[0-9]+}:{to:[0-9]+}[/]',
    • $findRangeEmpByDeptPageSql = "
    • SELECT emp_no, birth_date, first_name,
    •     last_name, gender, hire_date
    • FROM employees
    • JOIN dept_emp USING(emp_no)
    • JOIN departments USING(dept_no)"
    • WHERE dept_name=:dept"
    •     AND emp_no BETWEEN :from and :to
    • order by emp_no"
    • limit :limit OFFSET :offset";
  37. top of files
    • api/employees.php
    • <?php
    • use Slim\Http\Request;
    • use Slim\Http\Response;
    • use Slim\Http\Headers;

    • api/dbutils.php
    • <?php
    • require __DIR__ . '/../vendor/autoload.php';

    • vendor/autoload.php
    • <?php
    • require_once __DIR__ . '/composer/autoload_real.php';
    • return ComposerAutoloaderInit263c47d5b77b468de07d89baba4100da::getLoader();

    • bootstrap/app.php
    • <?php
    • require __DIR__ . '/../vendor/autoload.php';
    • $app = new \Slim\App(['settings'=>['DisplayErrorDetails' => true,]]);
    • require __DIR__ . '/../api/dbutils.php';
    • require __DIR__ . '/../api/departments.php';
    • require __DIR__ . '/../api/employees.php';
    • ?>

    • index.php
    • <?php
    • require __DIR__ . '/../bootstrap/app.php';
    • $app->run();
  38. prepared statements
    • $findOneEmpSql = "SELECT emp_no, birth_date, first_name, last_name, gender, hire_date
    • FROM employees
    • WHERE emp_no=:id";
    •     $findOneEmp = $connection->prepare($findOneEmpSql);

    • $app->get('/employees/{id:\d+}[/]',
    •     function(Request $request, Response $response, $args) {
    •         global $result;
    • //        $id = $args['id'];
    •         $id = $request->getAttribute('id');
    •         $result = findOneEmp($id);  
    •         return metaDataSingleGET("emp");
    •     }
    • );

    • function findOneEmp($id) {
    •     global $findOneEmp;
    •     if (!$findOneEmp) { initDB();    }
    •     $findOneEmp->bindParam(':id',$id);
    •     $findOneEmp->execute();
    •     $result = $findOneEmp->fetchAll(PDO::FETCH_ASSOC);
    •     return $result;
    • //    return json_encode($result);
    • }
  39. bootstrap/app.php
    • <?php
    • require __DIR__ .
    • '/../vendor/autoload.php';
    • $app = new \Slim\App(
    • ['settings'=>
    •   ['DisplayErrorDetails'=>
    •       true,]
    •  ]
    • );
    • require __DIR__ .
    •   '/../api/dbutils.php';
    • require __DIR__ .
    •   '/../api/departments.php';
    • require __DIR__ .
    •   '/../api/employees.php';
    • ?>
  40. db connection
    • $connection = "mysql:host=localhost;dbname=employees";
    • $user = "root";
    • $pwd = "mysql";
    • $db = new PDO($connection, $user, $pwd);
  41. get values from /employees/100:200?page=2
    • $app->get('/employees/{from:[0-9]+}:{to:[0-9]+}[/],
    • $from=$request->getAttribute('from');
    • $to=$request->getAttribute('to');
    •    or
    • $to=$args['to'];
    • $params=$request->getParams();
    • $pageNum=$params['page'];
  42. how to get data from curl post body
    • $data = json_decode(
    •   $request->getBody(), true);
    • $dob = $data['birth_date']
Author
slc53
ID
339070
Card Set
webServices
Description
webServices
Updated