Step 8: Combining the API with the form
We can now extend the form so that on button press we query the propublica API, get a list of senators and representatives and try to find one whose name matches our form input.
First we will extend our HTTP request to fetch all desired data. We will directly add this in the form's object editor as a new method:
class TestForm extends Morph {
async fetchSenatorsAndRepresentatives() {
let apiKey = "TPvKTecqWk9P0phZcoZydNUpoOXj6f6WMN7BYqaX",
congress = 115, // current congress, see https://projects.propublica.org/api-docs/congress-api/members/?#lists-of-members
chamber1 = "house",
chamber2 = "senate",
req1 = resource(`https://api.propublica.org/congress/v1/${congress}/${chamber1}/members.json`),
req2 = resource(`https://api.propublica.org/congress/v1/${congress}/${chamber1}/members.json`);
// add api key to both requests;
req1.headers["X-API-Key"] = apiKey;
req2.headers["X-API-Key"] = apiKey;
let data1 = await req1.makeProxied().readJson(),
data2 = await req2.makeProxied().readJson(),
members = data1.results[0].members.concat(data1.results[0].members);
return members;
}
/*...*/
}
Then, we can change the checkName method. We will simply compare our input with the concatenated first_name and last_name fields.
async checkName() {
let nameToFind = this.get("input line").input;
let members = await this.fetchSenatorsAndRepresentatives();
let found = members.find(ea => {
let name = ea.first_name + " " + ea.last_name;
return nameToFind === name;
});
let answer = found ?
this.printMember(found) :
`No one with the name "${nameToFind} found."`
$world.inform(answer);
}
If we find a matching result, we will want to print the data for the house or senate member in a readable format:
printMember(member) {
let {first_name, middle_name, last_name, title, state} = member;
let name = first_name;
if (middle_name)
name += " " + middle_name;
name += " " + last_name;
return `${ name } is ${ title } of ${ this.stateNames()[state] }`;
}
stateNames() {
return {
AK: "Alaska",
AL: "Alabama",
/*... see https://gist.github.com/mshafrir/2646763 for full list*/
}
When we now press the submit in our form we get: