Search code examples
google-webfonts

How can I sort fonts by category with the Google Webfonts API?


I'd like to be able to identify all of the fonts in a particular category (sans, sans-serif), which is possible from Google's web font viewer, but doesn't seem to work via the API.

https://developers.google.com/webfonts/docs/developer_api#Details


Solution

  • Short answer: get it from this gist

    Longer answer: Here is a tiny scala program to do this. You'll need to checkout googlefontdirectory project from http://code.google.com/p/googlefontdirectory to use this and change the basePath in the program below:

    import com.google.gson.GsonBuilder
    import org.apache.commons.io.IOUtils
    import java.io.FileInputStream
    import collection.mutable
    import collection.JavaConverters._
    
    object Webfonts {
      private val basePath = new java.io.File("/path/to/googlefontdirectory")
    
      def main(args: Array[String]) {
        val fontDetailsList = mutable.ListBuffer.empty[FontDetails]
        val categoryMap = mutable.Map.empty[String, java.util.List[String]]
    
        val gson = new GsonBuilder().setPrettyPrinting().create()
        for (font <- FontsList.fonts ) {
          fontDetailsList += gson.fromJson(IOUtils.toString(new FileInputStream(new java.io.File(basePath, font))), classOf[FontDetails])
        }
    
        fontDetailsList.filter(_.subsets.contains("latin")).foreach((font) => {
          val a = categoryMap.getOrElseUpdate(font.category, new java.util.ArrayList[String]())
          a.add(font.name)
        })
    
        val json = gson.toJson(categoryMap.asJava)
        println(json)
      }
    
    
      case class FontDetails(name: String, license: String, category: String, size: Int, subsets: Array[String]) {
        override def toString = category + " : " + name
      }
    
    }
    
    object FontsList {
      val fonts = Array(
        "./apache/aclonica/METADATA.json",
        "./apache/calligraffitti/METADATA.json",
        "./apache/cherrycreamsoda/METADATA.json",
        "./ufl/ubuntucondensed/METADATA.json",
        "./ufl/ubuntumono/METADATA.json"
    
      )
    }
    

    You can get the complete FontsList at https://gist.github.com/4085914