CSE 154

Section 11: Post Requests and Verification

Section Agenda

Review: GET vs. POST

Making POST Requests With fetch

Regex

Using a Trivia API with POST

Review: GET and POST

There are two common ways to make AJAX requests to a server.

  • GET requests
    • are the default, most of what we've seen have been GET requests
    • retrieve or get information from the server
  • POST requests
    • send information to the server
    • often change information on the server

Exercise 1: Posting with Postman

Recall how you would need to make API calls:

For GET requests, you can directly visit the URL on your browser and see the response.

For POST requests, that would be a bit more complicated. We've told you to test your POSTs by creating fetch calls with FormData. (See the slides below)

The following testing code is enough to make a POST request:


        // data parameters gets appended in FormData for POST requests (not in the url!)
        let params =  new FormData();
        params.append("location", "Equestira");
        params.append("group", "CSE 154 Wonderlads");
        params.append("members", "8");
        // make a POST request to httpbin.org/post with parameters attached
        fetch("https://httpbin.org/post", {method: "POST", body: params});
            

JS

Now there is an another way to test your APIs. Instead of venturing with the Chrome Developer tools or experimenting the URLs (which can be error prone at times), we can make calls with a dedicated program.

Introducing... Postman!

Ready, Set, Postman!

  1. To download Postman, visit https://www.getpostman.com/ and click on Download the App button.
  2. Under your operating system, click on the download button. Download will begin shortly.
  3. Depending on which operating system,
    • For Macintosh: you will need to unzip the zip and drag Postman to your Applications folder.
    • For Windows, you will need to double click the executable and follow the installation process.
  1. Once Postman is launched, you will need to skip signing in by clicking on the "Skip signing in and take me straight to the app" link at the very bottom of the login form.
  1. Close this welcome screen and you will be ready to make requests!

Making GET requests

The simplest of the request can be performed with Postman. By typing the URL into the bar and clicking on Send will make a GET request to the server.

Example 1 - GET the course website (https://courses.cs.washington.edu/courses/cse154/19sp/)

You can also insert query parameters (the stuff that goes after the url) to your GET request. They go into the Params input boxes.

Example 2 - GET https://httpbin.org/get w/ params: pony=rainbowdash and pokemon=ponyta

Most of the time you will be looking at the Body tab to see the output from the server. Occasionally you will need to see if the server is sending the correct Content-Type header. The headers can be accessed from the Headers tab.

Example 3 - Viewing headers

Practicing GET requests

Can you do the following?

  • Send a request to GET your favorite site. (if you don't have an example, go for
    http://www.csszengarden.com/) Admire their HTML source. (Solution)
  • Send a GET request to
    https://courses.cs.washington.edu/courses/cse154/webservices/postmantest/get.php
    (Solution)
  • Send a GET request to
    https://courses.cs.washington.edu/courses/cse154/webservices/postmantest/getwithparams.php (Solution)
    • Looks like the server has rejected because we're missing parameters. Send a request with a user parameter of the value ponyta. (Solution)
    • Oof so close! How about setting the user as rainbowdash? (Solution)

Making POST requests

Building POST requests on Postman is no more difficult than creating GET requests. Select POST from the dropdown list to the left of the URL box. Enter a POST URL into the box and hit send. You've just made your first POST request on Postman!

Example 4 - Making a POST request to https://httpbin.org/post

Since POST requests uses FormData instead of query parameters, we need to switch to the body tab in Postman. Select form-data from the radio buttons and enter your parameters.

Example 5 - Making a POST request to https://httpbin.org/post with data: name=rainbowdash, coolness=20-percent-cooler, and postman=rocks!

Practicing POST requests

Can you do the following?

  • Make a post request to https://courses.cs.washington.edu/courses/cse154/webservices/postmantest/post.php
    (Solution)
  • Make a post request to https://courses.cs.washington.edu/courses/cse154/webservices/postmantest/postwithparams.php.
    (Solution)
    • Let's try logging in with user as rainbowdash. (Solution)
    • Rainbow Dash has told me her password is ponyta. Set the password FormData as ponyta. (Solution)

Exercise 2: Posting with Fetch

Great work! Now it's time to try to replicate what you just did using JavaScript!

Note: One popular strategy for working with APIs is to use Postman to understand the API you are working with then duplicate the request with JavaScript.

Posting With Fetch

We have created a starter project for you to work with. It contains all the HTML and CSS needed as well as a starter JS file.

All you should need to do is make a POST request to the API with rainbowdash's username and password as you did in Postman.

https://courses.cs.washington.edu/courses/cse154/webservices/postmantest/postwithparams.php

Solution

Regex

Regex is a micro-language for describing patterns to match Strings against. A String can either match, or fail to match a regex pattern. By using it, you can verify that user input is valid, or find certain information in a body of text (we use it often in our testing scripts to verify code quality in your code!)

Meta-Cognition Strategy

Here is a good mental strategy to follow when constructing a Regex:

  1. Consider what kinds of strings you want to match
    • For example: valid email addresses
  2. Construct a general pattern that those strings follow. Try to get it as specific as possible.
    • For an email, the pattern is:
      EmailName@WebsiteName.DomainExtension
  3. Describe the structure of each part
    • For example, an emailName must have one or more characters, which can be letters, numbers, or certain special characters like _.
  4. Finally, convert each part of the pattern into the regex that matches that pattern.

Regex Practice

Regex is a very powerful tool, especially when validating text or implementing find/replace features. But it takes practice! Ahead you will find a collection of exercises to get you more practice.

Try to complete all of the quintessential exercises, but there are many more if you are looking for extra practice.

Remember that there are often several ways to write a correct regular expression!

Quintessential Regex Practice Exercises

Write regex that would match each of the following patterns:

  • UW Student Email (username@uw.edu or username@u.washington.edu, where username contains letters, numbers, and/or underscores, ignoring letter-casing) (try it) (one solution)
  • camelCased strings containing only letters and at least one capitalized letter (try it) (one solution)
  • A version of "Google" with an odd number of o's (try it) (one solution)
  • A real number such as 3.14 or -42.8775 (try it) (one solution)

Extra Exercises

Write regex that would match each of the following patterns:

  • DNA sequences (non-empty strings containing only A, C, G, T, ignoring letter-casing) (try it) (one solution)
  • A 16-digit credit card number, with optional dashes between every four digits (try it) (one solution)
  • Dollar amounts of at least $100.00 (try it) (one solution)
  • Strings that contain at least two consecutive vowels (A, E, I, O, or U), ignoring letter-casing (try it) (one solution)
  • Digimon names: strings starting with a capital letter and ending in "mon" (only letters otherwise) (e.g. "Agumon", "Gabumon", but not "mon, "agumon" or "Agu") (try it) (one solution)

Really Difficult Extra Exercises

Try these out if you want a challenge:

  • A https URL ending with "edu", "com", "org", or "gov" with website names consisting of letters, digits, and/or underscores, with at least one "." in the path (e.g. "https://www.cs.washington.edu") You should also match URLs that contain directories separated by slashes at the end ("https://google.com/images") and URLs with query parameters at the very end ("https://pets.com/pets.php?type=dog&breed=corgi") (try it) (one solution)
  • Strings that contain "cat" or "dog", but not both (ignoring letter-casing)
    Note that this is very difficult! (try it) (one solution)
  • Binary strings with at least one 1 and at most two 0's (try it) (one solution)

Validating a cafe order

Now we are going to write some more substantial POST request code, as well as some form-validation code.

Much of this cafe page is already implemented. The HTML and CSS is done, and it fetches menu items from a webservice and displays them on screen. You can download the starter code here.

You will implement submitting an order to the cafe webservice, first verifying that the user has entered their order information correctly. This can be done with JavaScript validation and/or HTML form element attributes.

Useful HTML input attributes

Attribute Description
type=number Invalidates input that is not a number, and provides buttons for increasing or decreasing the number
step=amount Defines the amount that the number input buttons increase or decrease the value, and also invalidates input that is not a multiple of the amount.
min=amount Invalidates number input that is less than the amount. There is also max.
type=email Invalidates invalid emails.
minlength=amount Invalidates text that is less than the amount in length. There is also maxlength.
required Invalidates empty input.
pattern="regex" Invalidates input that does not match the given regex pattern.

In init, Set up the "Submit Order" button so that it logs "Success" in the #submit-results element. You will want it to fail to submit if there are validation issues in the form inputs, so you should also add HTML validation (and JS validation if you need to) to verify the following properties:

  • The user must have selected a drink and a food item. Note that these radio buttons are generated dynamically in JS on line 143.
  • The tip must be a number greater than or equal to 0, with at most two digits after the decimal point if there is one. It is required
  • The address is required and should be more than 10 characters
  • The city must be filled out
  • The state must consist of two capital letters (e.g. "WA")

Note: If you ever want to validate elements not in a form, you can use element.checkValidity(), which returns true if it is valid and false otherwise.

Change the valid behavior to submit a POST request to the following endpoint with the order details.

https://courses.cs.washington.edu/courses/cse154/webservices/mowgliscafe/mowgliscafe.php

Your request should match the format defined in the API documentation.

Print the response from the server into the #order-results element.

Finally, add some CSS to make the page more intuitive. Input elements that are invalid should be highlighted with a red border.

You can access the validity of an element in CSS with the :valid and :invalid CSS pseudo-classes.

Solution