Git Product home page Git Product logo

numbers_api's Introduction

Bring meaning to your metrics and stories to your dates with our API of interesting number facts.

Getting Started

Installing Dependencies

npm install

Run script to implement SASS styling from compass.

npm run scss

Start server on http://localhost:8124/

npm start

Running into issues

This API was built with Node version 10. If you experience issues while installing npm dependencies, try running install process with an older version of node. Versions 15 and 12 are able to run server.

See Node Version Manager for a great tool for switching between node versions.

URL Structure

Just hit http://numbersapi.com/number/type to get a plain text response, where

  • type is one of trivia, math, date, or year. Defaults to trivia if omitted.
  • number is
    • an integer, or
    • the keyword random, for which we will try to return a random available fact, or
    • a day of year in the form month/day (eg. 2/29, 1/09, 04/1), if type is date
    • ranges of numbers
http://numbersapi.com/42
⇒ 42 is the result given by Google and Bing for the query "the answer to life the universe and everything".

http://numbersapi.com/2/29/date
⇒ February 29 is the day in 1504 that Christopher Columbus uses his knowledge of a lunar eclipse to convince Native Americans to provide him with supplies.

http://numbersapi.com/random/year
⇒ 2013 is the year that China will attempt its first unmanned Moon landing.

Usage Examples

jQuery

HTML:

We now have more users than <span id="number"></span>!

JavaScript:

$.get('http://numbersapi.com/1337/trivia?notfound=floor&fragment', function(data) {
    $('#number').text(data);
});

Direct cross-origin requests like this are possible on browsers that support CORS. Live demo on JSFiddle.

Query Parameter Options

Fragment

Return the fact as a sentence fragment that can be easily included as part of a larger sentence. This means that the first word is lowercase and ending punctuation is omitted. For trivia and math, a noun phrase is returned that can be used in a sentence like "We now have more users than [fact as fragment]!".

http://numbersapi.com/23/trivia?fragment
⇒ the number of times Julius Caesar was stabbed

http://numbersapi.com/1969/year?fragment
⇒ an estimated 500 million people worldwide watch Neil Armstrong take his historic first steps on the Moon

Notfound

The notfound field tells us what to do if the number is not found. You can give us:

  • default to return one of our pre-written missing messages, or a message you supply with the default query field. This is the default behaviour.
    http://numbersapi.com/314159265358979
    ⇒ 314159265358979 is a boring number.
  • floor to round down to the largest number that does have an associated fact, and return that fact.
    http://numbersapi.com/35353?notfound=floor
    ⇒ 35000 is the number of genes in a human being.
  • ceil, which is like floor but rounds up to the smallest number that has an associated fact.
    http://numbersapi.com/-12344/year?notfound=ceil
    ⇒ 98 BC is the year that the Senate passes the Lex Caecilia Didia which bans omnibus bills.

Combine with the fragment option to produce interesting facts about, for example, the number of page shares.

Default

The value of the default query field tells us what to return if we don't have a fact for the requested number.

http://numbersapi.com/1234567890987654321/year?default=Boring+number+is+boring.
⇒ Boring number is boring.

See the HTML embed tag usage example.

Min and Max

Restrict the range of values returned to the inclusive range [min, max] when random is given as the number.

http://numbersapi.com/random?min=10&max=20
13 is the number of provinces and territories in Canada.

JSON

Include the query parameter json, or set the HTTP header Content-Type to application/json, or set the HTTP header Accept to application/json to return the fact and associated meta-data as a JSON object, with the properties:

  • text: A string of the fact text itself.
  • found: Boolean of whether there was a fact for the requested number.
  • number: The floating-point number that the fact pertains to. This may be useful for, eg. a /random request or notfound=floor. For a date fact, this is the 1-indexed day of a leap year (eg. 61 would be March 1st).
  • type: String of the category of the returned fact.
  • date (sometimes): A day of year associated with some year facts, as a string.
  • year (sometimes): A year associated with some date facts, as a string.
http://numbersapi.com/random/year?json
⇒ {
    "text": "2012 is the year that the century's second and last solar transit of Venus occurs on June 6.",
    "found": true,
    "number": 2012,
    "type": "year",
    "date": "June 6"
}

Batch Requests

To get facts about multiple numbers in one request, specify ranges for number in http://numbersapi.com/number/type.

A number range (inclusive) is specified as min..max. Separate multiple ranges and individual numbers with , (a comma).

The response format will always be a JSON map from numbers to facts, of at most 100 numbers. The query parameter json may still be used to specify whether individual facts will be returned as string literals or JSON objects.

http://numbersapi.com/1..3,10
⇒ {
    "1": "1 is the number of dimensions of a line.",
    "2": "2 is the number of polynucleotide strands in a DNA double helix.",
    "3": "3 is the number of sets needed to be won to win the whole match in volleyball.",
    "10": "10 is the highest score possible in Olympics gymnastics competitions."
}

Deprecated Features

Callback

To use JSONP, pass to the callback query the name of the JavaScript function to be invoked. The response will be that function called on the fact text as a string literal.

http://numbersapi.com/42/math?callback=showNumber
⇒ showNumber("42 is the 5th Catalan number.");

See the JSONP usage example.

JSONP

...is supported with the query field callback:

<span id="number-fact"></span>

<script>
    function showNumber(str) {
        document.getElementById('number-fact').innerText = str;
    }

    (function() {
        var scriptTag = document.createElement('script');
        scriptTag.async = true;
        scriptTag.src = "http://numbersapi.com/42/math?callback=showNumber";
        document.body.appendChild(scriptTag);
    })();
</script>

Live demo on JSFiddle.

Write

We do not recommend using document.write() because of possible cross-site scripting attacks.

Returns the text response wrapped in a call to document.write(). Note that using this query parameter is equivalent to and just a shorthand of ?callback=document.write.

http://numbersapi.com/42/math?write
⇒ document.write("42 is the 5th Catalan number.");

HTML Embed

Add write to your query string to have the response text wrapped in document.write(). Now you can stick just a single <script> directly where the fact should go.

Did you know 2012 is the year that <script src="http://numbersapi.com/2012/year?write&fragment"></script>?

Note that this may degrade page load speed. Live demo on JSFiddle.

Contributing

Numbers API is an evolving project. If you would like to contribute to the code base, suggest any ideas, or even just submit a number fact, please visit our Github.

numbers_api's People

Contributors

anita-lee avatar austinschao avatar ben-hong avatar calebthewood avatar christian-alcalde avatar dependabot[bot] avatar divad12 avatar ericsohng avatar gary-rivera avatar jacobson-ben avatar joheyjo avatar kathyn138 avatar lynecha avatar martinjwkim avatar mduan avatar mmmaaatttttt avatar nalipp avatar ngjamesng avatar paigegodfrey avatar richarddowdy avatar sairina avatar stephenisau avatar winniegotyu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

numbers_api's Issues

Investigate aws_setup

since we're hosting on DigitalOcean, not sure whether we need this folder. Investigate.

Estimated points: 1

Get rid of email

Problem description: Right now the API docs say that if you have a suggestion for adding a number fact, you should email it. But this isn't maintainable. It would be better if we could link people to this repo and encourage them to open up a PR with their new fact.

Separate shared_utils into a common package

Problem description:

This file consists of js code that is meant to be shared across both front and back-end: https://github.com/rithmschool/numbers_api/blob/master/public/js/shared_utils.js

However, because it is served on the front-end, it has to be cross-browser compatible, may be more difficult to refactor, etc. Would be better to have this be in a node environment so that it's easier to upgrade.

Suggested solution:

We could follow this pattern

https://stackoverflow.com/questions/56591385/load-same-file-in-front-end-and-back-end

I recommend doing this before adding react so that the project is all ready to slot in a frontend folder. Would also allow us to refactor the file itself to a more modern style.

Refactor frontend into React

cuz jquery is so 2012.

Problem description:

frontend is old.

Suggested solution:

Refactor to a more modern architecture.

(See #47 for a related issue)

Remove document.write, jsonp

Problem description:
The original docs reference document.write, and jsonp.
These features are outdated and likely need to be removed from the project.

Suggested solution:
Remove this functionality from the codebase and update the docs.

Documentation rendering bug

Problem description:

There are several places in the docs where words are wrapped in backticks, eg here:

Screen Shot 2021-04-30 at 11 56 08 AM

The backticks should be detected and parsed as code elements, as they are here for the words in front of a darker background.

Screen Shot 2021-04-30 at 11 57 11 AM

Suggested solution:

Investigate and fix all occurrences so that the docs render properly.

Remove vendor assets

there's a bunch of stuff in /public that shouldn't be in version control (eg. bootstrap). Let's relegate as much as possible to node_modules.

Add ability to get facts about sequences of numbers

This website has random facts about sequences of integers: https://oeis.org/
looks like they have some json api endpoints too: https://stackoverflow.com/questions/5991756/programmatic-access-to-on-line-encyclopedia-of-integer-sequences

It could be cool to have an endpoint to get a random fact about a sequence of numbers, eg. /v2/sequences?nums=1,2,7,10 would get a random sequence containing the numbers 1, 2, 7, and 10, and return info about it to the user

create Wikidata GraphQL implementation

Gather data from wikidata and create queries for art museums and tourist attractions. Get the location label, coordinates, and visitors of museums and tourist attractions. Sanitize the data and create queries that returns name, visitors, and coordinates based on the keyword that is inputted in the query. Write tests for graphQL.

Create a dummy data file and refactor tests

Currently, a lot of tests are being run on the main database. This would cause issues when new data is scraped, because the data wouldn't match anymore. Create a dummy data file so the data doesn't change and refactor the tests based on the dummy data file.

Add tests to all routes

Currently no routes have tests. Let's make sure the app is well-tested.

Estimated points: 6

Add debouncing mouse-wheel action for API calls

Problem description:

When scrolling/mouse-wheeling over the element with id #counter (see left side of screenshot), the number increments/decrements by one until your mouse-wheel action stops.

Screen Shot 2020-07-21 at 8 41 03 PM

Steps to Reproduce:

The following steps can reproduce the issue locally.

  1. In public/js/script.js, add a temporary console.log() to the .mousewheel callback function.
  2. In routes/api.js, add a temporary console.log() to the factResponse function.
  3. Start the server, and scroll over the element as described earlier. Observe the front-end and back-end console as you mouse-wheel.

The current behavior:

The current behavior currently calls the API from the current number(let's say 42) through to the number you stop at(let's say 1042) and can be done in a matter of seconds. That is one thousand API calls.

The expected behavior:

The API doesn't need to be called for every number, especially if the user changes the number multiple times within a second. At minimum, using the above scenario, the API should call for 42 and 1042. A better UX would be to call just a few in between as you increment.

Suggested solution:

Implement some debouncing for this feature to limit the amount of calls to one API call every ~0.3 - 1 seconds, or whatever amount feels right.
https://css-tricks.com/debouncing-throttling-explained-examples/

Relevant code snippet:

.mousewheel(function(event, delta) {
$('#counter').counter(delta > 0 ? 'increment' : 'decrement');
event.preventDefault();
});

Update ReadMe re: setup environment

Problem description:

Readme does not describe requirements to get project running locally.

The current behavior:

Projects needs to run on older versions of node. Npm install results in many error messages and server does not start.

The expected behavior:

Unless otherwise noted, project should run on current stable versions of node.

Suggested solution:

Create section in ReadMe to describe setting up local environment.

Estimated points:

.5 point

Test routes api.js

Problem description:
The logic in these routes need to be separated so that they are easier to test.

Suggested solution:
Write tests as part of the refactor.

Update interactive requests

Problem description:
There are existing interactive requests in the docs but easy to miss.

Suggested solution:
Document the existing endpoints and create a sandbox to try the requests.
Something similar to the sandbox in the pokemon api https://pokeapi.co/

re-enable logging

there's a function that used to be part of the project which would log every request (

function logRequest(req) {
) and occasionally write these logs to a file. There were also two endpoints that would reveal summary statistics based on these log files: https://github.com/rithmschool/numbers_api/blob/master/app.js#L143-L149

However, the logging was consuming >100% CPU, mostly likely because the files were getting quite large and so reading / writing was expensive. Would be nice to bring this feature back, but we should think about how to better support it at current scale. (Redis? DB? something else?)

Repo does not ignore .sass-cache/ directory

Problem description:
When compiling the CSS, the .sass-cache directory is created, and is tracked by git.

Steps to Reproduce:

  1. In the home directory of the repo, run compass compile public to generate the front end styling.
  2. run git status and you will see the untracked .scssc files.

The current behavior:
The .scssc files are being tracked by git when we generate the files.

The expected behavior:
The .scssc files shouldn't be tracked by git when we generate the files.

Suggested solution:

add .sass-cache/ to the .gitignore file.

Relevant code snippet:

.sass-cache/

Estimated points:
0.01, since this is a one line fix.

Modern JS refactor

Most of this code was written prior to ES2015, so it could use a refactor for 2020.

remove unused text files

Problem description:

I don't know what's being used and what's not, but there's a smattering of random files in the project that could potentially be removed. eg this and this.

Suggested solution:

Analyze which files aren't being used, and DESROY THEMMMM

Test the frontend

Problem description:
Right now the frontend uses jQuery and sass, there are no frontend tests.

Suggested solution:
Either test the existing jQuery code, or refactor the front end to use React and React testing library.
Any refactor should maintain the existing SASS code.

Sanitize raw skyscraper data & create GraphQL endpoint for it

Sanitizing Data

Raw skyscraper data has been scraped from WikiData inside the wikidata folder under rawSkyscraper.js. The data needs to be sanitized.

The query used was this one here. At the current time of writing this, the height attribute is very inconsistent

For example:

The larger number (269) is the height in feet while the smaller number (82) is the height in meters.
Screen Shot 2021-05-20 at 1 21 43 PM

However, not all entries with two heights go by this convention. The larger number (450) is the height at the top of the building in feet while the smaller number's (316) unit is still meters, but the height of the top floor.
Screen Shot 2021-05-20 at 1 23 34 PM

One last example of inconsistent data points. The smaller number (442) is the height of the building in meters, but 1098 doesn't seem to be associated with this building, according to the Wikipedia article
Screen Shot 2021-05-20 at 1 31 01 PM


Create function to parse data

Once the data is sanitized, create a function to parse the data out for endpoint usage. Maybe the structure of the return could look something like

[
  {
    name: "Zifeng Tower",
    height: int,
    elevators: int,
    coordinates: string
  },
  ...
]

Create GraphQL endpoint

Create a new type, query, and resolver for the GraphQL endpoint to point to the skyscraper data.

Decide what to do about Python code

Problem description:

Related to #14 but different. The Python files in the models folder are Python2, old and in need of an update. Feels a bit strange to have Python files in here, but I'd be ok with an upgrade to Python3 or a re-implementation in node instead.

Suggested solution:

If we stay in python, we'll need to:

if we move to node, we'll need to

  • add cheerio as a dependency
  • migrate each file to JS

We should break this up into sub-issues, but not until we make a decision about JS vs Python.

Investigate Deployment options

We don't currently have an automated deployment workflow for our hosting provider (Digital Ocean). Let's set up CI for this project.

npm run generate_facts

Problem description:
Need to figure out how to expand / improve facts data

The current behavior:
Facts are generated and stored in files on the server #14

The expected behavior:
Create a npm script gets new facts or updates current facts

req.param() audit

In express v2, you could use a function req.param() to access data coming from either the url or the query string. This was deprecated and now you just access req.params or req.query directly. however, in the express version bump i made for the project i just automatically changed req.param() to req.params, even if the data was coming from the query string. There may be bugs because of this, let's audit every place we reference req.params and be sure that we're trying to use a req parameter and not something else (e.g. a query string parameter)

clearer documentation around models folder

There's a bunch of python files in /models used for scraping -- but it seems like these were just run in order to generate text files. Let's clarify how these files fit into the general structure of the project. Would be good to add to the Wiki on GitHub explaining this.

Remove ruby dependencies

There's currently a Gemfile in the project for static asset compilation (I think SCSS to CSS)? Whatever the case, let's get rid of this -- if we need SCSS compilation, let's do it strictly from within the node ecosystem.

Content-type vs Accept headers

The docs state that you can set the response to be json by setting a content-type header in the request. However, content-type is typically for the content type of the request data, not the response data. For the latter, we should use the Accept header. We should modify the docs and the server to support setting the Accept header (right now i don't think you can set either header via ajax bc cors).

Longer term we should also remove this feature when setting content-type and just use accept. But since this introduces a breaking change, we should reserve it for a major version change (i.e. not v1.1)

Readme audit.

The README needs to have line breaks between all section headings, otherwise the markdown won't get parsed correctly. Here's an example (we shouldn't see backticks around json, for example):

Screen Shot 2020-06-15 at 1 37 35 PM

Remove Makefile

Anything we can do in here, let's do from the scripts key in package.json

Search by fact data

You can get facts by number, but it could be nice to implement a search feature where you can search for a keyword (e.g. baseball) and get a list of facts that match that keyword.

This might be more work than it seems if searching through the text files is slow. But we can save optimization for a future issue.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.