Categories
Useful APIs

Useful Free APIs — Animals and Pets

In the software development world, practice makes perfect. Therefore, we should find as many ways to practice programming as possible. With free public APIs, we can practice programming by creating apps that use those APIs.

In this article, we’ll look at some practice project ideas that can use some of those APIs.

Animal APIs

There are several APIs that let us get animal data.

Cat Facts

The Cat Facts API lets us get facts about cats.

No authentication is required. It doesn’t support CORS.

Cats API

Cats API is an API that lets us get cat pictures from Tumblr.

We can use it to get breeds, categories, images, and more.

An API key is required for authentication.

Dogs API

The Dogs API lets us get data from the Stanford Dogs Dataset.

Authentication isn’t required, and we can use it to get data like breeds and pictures.

HTTPCat

The HTTPCat API lets us get cat pictures from the API.

It returns responses with cat pictures with different response status codes.

IUCN Red List API

The IUCN Red List API lets us get data for various kinds of animals.

We can get species data, species category, names, species by country, and more.

Also, we can get threats of different species, habitats of different species, conservation measures, and other habitat data.

Conservation, plant growth, comprehensive groups, and more are also available.

An API token is required to use this API.

Movebank REST API

The Movebank REST API has movement and migration data for animals.

It provides us with endpoints that get us migration data, sensor types, description of entities, even data of sensors, and more.

It’s used to track the movement of animals.

Data access privileges can be controlled per user.

The data is available in CSV or JSON format.

Petfinder

The Petfinder API lets us get animals that are available to the client.

We can get animal types, single animal types, animal breeds, organizations, and more.

This API can be accessed with the client ID and client secret.

A Petfinder account is required.

PlaceGOAT

The PlaceGOAT API lets us get goat images for placeholders in our app.

We can use it to get images with different width and height.

Authentication isn’t required to access the API.

RandomCat

The RandomCat API gives us a URL for a random picture of a cat.

No authentication is required to access this API.

RandomDog

The RandomDog API gives us a URL for a random picture of a dog.

No authentication is required to access this API.

RandomFox

The RandomDog API gives us a URL for a random picture of a fox.

No authentication is required to access this API.

RescueGroups

The RescueGroups API lets us get pet adoption data with its API.

We can get data for various species, events, donations, sponsorships, locations, and more.

Authentication is required to access this API.

Shibe.Online

The Shibe.Online API lets us get a random picture of Shiba Inus, cats, or birds.

Authentication isn’t required to access this API.

Conclusion

There are many APIs we can use to get animal data and pictures.

Categories
React D3

Adding Graphics to a React App with D3 — Bar Chart

D3 lets us add graphics to a front-end web app easily.

Vue is a popular front end web framework.

They work great together. In this article, we’ll look at how to add graphics to a Vue app with D3.

Create a Bar Chart

We can create a bar chart with D3 in our React app by reading in the data, creating the axes, and adding the bars.

For example, we can write:

public/data.csv

year,population
2006,20
2008,25
2010,38
2012,61
2014,43
2016,26
2017,62

src/App.js

import React, { useEffect } from "react";
import * as d3 from "d3";

const createBarChart = async () => {
  const svg = d3.select("svg"),
    margin = 200,
    width = svg.attr("width") - margin,
    height = svg.attr("height") - margin;

  svg
    .append("text")
    .attr("transform", "translate(100,0)")
    .attr("x", 50)
    .attr("y", 50)
    .attr("font-size", "20px")
    .attr("class", "title")
    .text("Population bar chart");

  const x = d3.scaleBand().range([0, width]).padding(0.4),
    y = d3.scaleLinear().range([height, 0]);
  const g = svg.append("g").attr("transform", "translate(100, 100)");
  const data = await d3.csv("data.csv");

  x.domain(
    data.map(function (d) {
      return d.year;
    })
  );
  y.domain([
    0,
    d3.max(data, function (d) {
      return d.population;
    })
  ]);

  g.append("g")
    .attr("transform", `translate(0, ${height})`)
    .call(d3.axisBottom(x))
    .append("text")
    .attr("y", height - 250)
    .attr("x", width - 100)
    .attr("text-anchor", "end")
    .attr("font-size", "18px")
    .attr("stroke", "blue")
    .text("year");

  g.append("g")
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", 6)
    .attr("dy", "-5.1em")
    .attr("text-anchor", "end")
    .attr("font-size", "18px")
    .attr("stroke", "blue")
    .text("population");

  g.append("g").attr("transform", "translate(0, 0)").call(d3.axisLeft(y));
  g.selectAll(".bar")
    .data(data)
    .enter()
    .append("rect")
    .attr("class", "bar")
    .style("fill", "lightgreen")
    .on("mouseover", onMouseOver)
    .on("mouseout", onMouseOut)
    .attr("x", function (d) {
      return x(d.year);
    })
    .attr("y", function (d) {
      return y(d.population);
    })
    .attr("width", x.bandwidth())
    .transition()
    .ease(d3.easeLinear)
    .duration(200)
    .delay(function (d, i) {
      return i * 25;
    })
    .attr("height", function (d) {
      return height - y(d.population);
    });

  function onMouseOver(d, i) {
    d3.select(this).attr("class", "highlight");

    d3.select(this)
      .transition()
      .duration(200)
      .attr("width", x.bandwidth() + 5)
      .attr("y", function (d) {
        return y(d.population) - 10;
      })
      .attr("height", function (d) {
        return height - y(d.population) + 10;
      });

    g.append("text")
      .attr("class", "val")
      .attr("x", function () {
        return x(d.year);
      })
      .attr("y", function () {
        return y(d.value) - 10;
      });
  }

  function onMouseOut(d, i) {
    d3.select(this).attr("class", "bar");

    d3.select(this)
      .transition()
      .duration(200)
      .attr("width", x.bandwidth())
      .attr("y", function (d) {
        return y(d.population);
      })
      .attr("height", function (d) {
        return height - y(d.population);
      });

     d3.selectAll(".val").remove();
  }
};

export default function App() {
  useEffect(() => {
    createBarChart();
  }, []);

  return (
    <div className="App">
      <svg width="500" height="500"></svg>
    </div>
  );
}

We add the svg element in our template.

Then we create the title by writing:

svg
  .append("text")
  .attr("transform", "translate(100,0)")
  .attr("x", 50)
  .attr("y", 50)
  .attr("font-size", "20px")
  .attr("class", "title")
  .text("Population bar chart");

x and y are the x and y coordinates of the top left corner of the text.

transform transforms the text by translating it.

The font-size has the font size for the title.

Then we create the x and y ranges we use for the axes:

const x = d3.scaleBand().range([0, width]).padding(0.4),
  y = d3.scaleLinear().range([height, 0]);
const g = svg.append("g").attr("transform", "translate(100, 100)");
const data = await d3.csv("data.csv");

x.domain(
  data.map(function(d) {
    return d.year;
  })
);
y.domain([
  0,
  d3.max(data, function(d) {
    return d.population;
  }),
]);

We set the domain of x and y with the domain method.

Then we create the x-axis with the axisBottom method:

g.append("g")
  .attr("transform", `translate(0, ${height})`)
  .call(d3.axisBottom(x))
  .append("text")
  .attr("y", height - 250)
  .attr("x", width - 100)
  .attr("text-anchor", "end")
  .attr("font-size", "18px")
  .attr("stroke", "blue")
  .text("year");

The attr method sets all the CSS styles.

Then we add the label for the y-axis by writing:

g.append("g")
  .append("text")
  .attr("transform", "rotate(-90)")
  .attr("y", 6)
  .attr("dy", "-5.1em")
  .attr("text-anchor", "end")
  .attr("font-size", "18px")
  .attr("stroke", "blue")
  .text("population");

Then we add the y-axis itself by writing:

g.append("g").attr("transform", "translate(0, 0)").call(d3.axisLeft(y));

And we add the bars by writing:

g.selectAll(".bar")
  .data(data)
  .enter()
  .append("rect")
  .attr("class", "bar")
  .style("fill", "lightgreen")
  .on("mouseover", onMouseOver)
  .on("mouseout", onMouseOut)
  .attr("x", function(d) {
    return x(d.year);
  })
  .attr("y", function(d) {
    return y(d.population);
  })
  .attr("width", x.bandwidth())
  .transition()
  .ease(d3.easeLinear)
  .duration(200)
  .delay(function(d, i) {
    return i * 25;
  })
  .attr("height", function(d) {
    return height - y(d.population);
  });

We add a mouseover event listener that expands the bar when we hover our mouse over it.

Also, we add the mouseout event listener to restore the bar to its original size when we move our mouse away from the bar.

We set the x and y attributes so that we can position it on the x-axis.

Then, we add some transition to it when it’s loading with the transition , ease , and duration calls.

And finally, we set the height of the bar to by setting the height attribute in the last attr call.

Conclusion

We can create a bar chart from CSV data with D3.

Categories
React D3

Adding Graphics to a React App with D3 — Loading JSON, XML, and TSV

D3 lets us add graphics to a front-end web app easily.

Vue is a popular front end web framework.

They work great together. In this article, we’ll look at how to add graphics to a Vue app with D3.

Loading JSON

We can load JSON stored in an external file.

For example, we can write:

public/data.json

[
  {
    "name": "John",
    "age": 30,
    "city": "New York"
  },
  {
    "name": "Jane",
    "age": 20,
    "city": "San Francisco"
  }
]

src/App.js

import React, { useEffect } from "react";
import * as d3 from "d3";

const readJson = async () => {
  const data = await d3.json("/data.json");
  for (const { name, age } of data) {
    console.log(name, age);
  }
};

export default function App() {
  useEffect(() => {
    readJson();
  }, []);

  return <div className="App"></div>;
}

We have the readJson function that reads data from data.json .

And then we loop through the data array that has the parsed entries.

We get:

John 30
Jane 20

logged.

Loading XML File

D3 also comes with the d3.xml method to load the XML file.

For instance, we can write:

public/data.xml

<?xml version="1.0" encoding="UTF-8"?>
<root>
<row>
    <name>John</name>
    <age>30</age>
</row>
<row>
    <name>Jane</name>
    <age>32</age>
</row>
</root>

src/App.js

import React, { useEffect } from "react";
import * as d3 from "d3";

const readXml = async () => {
  const data = await d3.xml("/data.xml");
  for (const n of data.documentElement.getElementsByTagName("name")) {
    console.log(n.textContent);
  }
};

export default function App() {
  useEffect(() => {
    readXml();
  }, []);

  return <div className="App"></div>;
}

In the readXml function, we call d3.xml to read the data.

Then we get the elements with the name tag and then loop through the returned items.

Loading Tab Separated Files

We can load tab-separated files with the d3.tsv method.

For example, we can write:

public/data.tsv

name age city
John 30 New York
Jane 20 San Francisco

src/App.js

import React, { useEffect } from "react";
import * as d3 from "d3";

const readTsv = async () => {
  const data = await d3.tsv("/data.tsv");
  for (const { name, age, city } of data) {
    console.log(name, age, city);
  }
};

export default function App() {
  useEffect(() => {
    readTsv();
  }, []);

  return <div className="App"></div>;
}

We call the readTsv method.

And then we loop through the parsed rows and log them.

Then we get:

John 30 New York
Jane 20 San Francisco

logged in the console.

Conclusion

We can load CSV, TSV, XML, and JSON files with D3 in our Vue app.

Categories
React D3

Adding Graphics to a React App with D3 — Format TSVs and Load CSVs

D3 lets us add graphics to a front-end web app easily.

Vue is a popular front end web framework.

They work great together. In this article, we’ll look at how to add graphics to a Vue app with D3.

tsvFormat

We can use the tsvFormat method to convert an array of objects into a tab-separated string.

For example, we can write:

import React, { useEffect } from "react";
import * as d3 from "d3";

const data = [
  { year: 2011, population: 10 },
  { year: 2012, population: 20 },
  { year: 2013, population: 30 }
];
export default function App() {
  useEffect(() => {
    const string = d3.tsvFormat(data, ["year", "population"]);
    console.log(string);
  }, []);

  return <div className="App"></div>;
}

Then the string is:

year population
2011 10
2012 20
2013 30

We pass in an array of objects as the first argument.

The 2nd argument has an array of the column heading strings.

tsvFormatRows

We can call the tsvFormatRows method to convert a nested array into a tab-separated string.

For example, we can write:

import React, { useEffect } from "react";
import * as d3 from "d3";

const data = [
  [2011, 10],
  [2012, 20],
  [2013, 30]
];
export default function App() {
  useEffect(() => {
    const string = d3.tsvFormatRows(data);
    console.log(string);
  }, []);

  return <div className="App"></div>;
}

to use the tsvFormatRows method with the data .

Then we get:

2011 10
2012 20
2013 30

logged.

Timer

We can add timers that come with D3 to add animations to a React app.

We can call the d3.timer method to create a timer:

import React, { useEffect } from "react";
import * as d3 from "d3";

export default function App() {
  useEffect(() => {
    const timer = d3.timer(function (duration) {
      console.log(duration);
      if (duration > 150) {
        timer.stop();
      }
    }, 100);
  }, []);

  return <div className="App"></div>;
}

We call timer with a callback that has the duration parameter with the callback in the duration.

Then if the duration is bigger than 150ms, then we call timer.stop to stop the timer.

Loading CSV

We can load CSVs in our React app with the d3.csv method.

For example, we can write:

public/data.csv

name,age
John,30
Jane,32

src/App.js

import React, { useEffect } from "react";
import * as d3 from "d3";

const readCsv = async () => {
  const data = await d3.csv("/data.csv");
  for (const { name, age } of data) {
    console.log(name, age);
  }
};

export default function App() {
  useEffect(() => {
    readCsv();
  }, []);

  return <div className="App"></div>;
}

We have the readCsv function to read the data from public/data.csv .

Then we loop through the data array, which has the parsed CSV rows.

And we get:

John 30
Jane 32

Conclusion

We can read and create CSVs and TSVs with D3 in our React app.

Categories
React D3

Adding Graphics to a React App with D3 — CSVs and TSVs

D3 lets us add graphics to a front-end web app easily.

Vue is a popular front end web framework.

They work great together. In this article, we’ll look at how to add graphics to a Vue app with D3.

csvParseRows

We can use the csvParseRows method to parse CSV strings into an array of objects.

For example, we can write:

import React, { useEffect } from "react";
import * as d3 from "d3";

const string = `2011,10\n2012,20\n2013,30\n`;

export default function App() {
  useEffect(() => {
    const data = d3.csvParseRows(string, function ([year, population]) {
      return {
        year: new Date(+year, 0, 1),
        population
      };
    });
    console.log(data);
  }, []);

  return <div className="App"></div>;
}

We call csvParseRows with the CSV strings as the first argument.

The callback has the parsed entry and we can return what we want from it.

csvFormat

The csvFormat method formats the CSV rows and columns.

For instance, we can write:

import React, { useEffect } from "react";
import * as d3 from "d3";

const data = [
  { year: 2011, population: 10 },
  { year: 2012, population: 20 },
  { year: 2013, population: 30 }
];
export default function App() {
  useEffect(() => {
    const string = d3.csvFormat(data, ["year", "population"]);
    console.log(string);
  }, []);

  return <div className="App"></div>;
}

We pass in an array of objects as the first argument.

Then we pass in an array of strings with the column names.

And then we get the value of string , which is the CSV string. Its value is:

year,population
2011,10
2012,20
2013,30

tsvParse

The tsvParse method lets us parse tab-separated strings.

For instance, we can write:

import React, { useEffect } from "react";
import * as d3 from "d3";

const string = `year\tpopulation\n2011\t10\n2012\t20\n2013\t30\n`;

export default function App() {
  useEffect(() => {
    const data = d3.tsvParse(string, function ({ year, population }) {
      return {
        year: new Date(+year, 0, 1),
        population
      };
    });
    console.log(data);
  }, []);

  return <div className="App"></div>;
}

We have a tab-separated string and call tsvParse with it.

Then on the callback, we destructure the year and population properties from the parsed entry in the parameter.

And we return the object to return what we want.

tsvParseRows

The tsvParseRows method lets us parse the tab-separated string rows without the headings.

For example, we can write:

import React, { useEffect } from "react";
import * as d3 from "d3";

const string = `2011t10n2012t20n2013t30n`;

export default function App() {
  useEffect(() => {
    const data = d3.tsvParseRows(string, function ([year, population]) {
      return {
        year: new Date(+year, 0, 1),
        population
      };
    });
    console.log(data);
  }, []);

return <div className="App"></div>;
}

We pass in a string without the headings.

Then we call tsvParseRows with the string and the callback that has the properties of the parsed row destructured.

And we return the object that we want to return for each entry.

Conclusion

We can parse and create CSVs and TSVs with D3 and use them in our React app.