-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1_API_intro.Rmd
More file actions
92 lines (61 loc) · 2.05 KB
/
1_API_intro.Rmd
File metadata and controls
92 lines (61 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
---
title: "methods@manchester: API intro"
author: "Renata Topinkova"
date: "14 06 2022"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Load libraries
```{r libs}
#install.packages("package_name")
library(httr)
library(dplyr)
```
## Query API
API: https://api.nationalize.io
Parameters are organized as key - value pairs. See the allowed parameters in the API documentation.
```{r endpoints}
# Specify the endpoint
endpoint <- "https://api.nationalize.io?"
# Query the API
req <- GET(endpoint,
# specify the parameters for your query
query = list(
name = "Renata"
))
# Alternatively: GET("https://api.nationalize.io?name=renata")
# Explore what we've collected
req
```
--> Status 200 - ok, query successful
### Parsing the content of our query
To parse the content of the API query, we need the `content` function from the `httr` package.
`content` function has `as` argument that specifies how the content will be parsed (`raw`, `text`, `parsed`).
If you do not specify the argument, R will make its best guess to parse the data. Sometimes it's accurate, sometimes not - you can play around with it.
Alternatively, you can parse json content with `jsonlite` package.
```{r}
# See the content of the query
content(req)
# Play around with the parsing
content(req, "text") # js notation
content(req, "raw") # not human-readable
content(req, "parsed") # best version - list
```
## Your turn!
### 1.1. Query: Your name.
Query the Nationalize.io API (https://api.nationalize.io) to predict the nationality of your name.
```{r}
```
### 1.2. Query Genderize.io I: Name
Look up the documentation for a new API https://genderize.io/
Query the API to predict the gender for the name "Jessie".
```{r}
```
### 1.3. Query Genderize.io II: Name & Country
Query the API https://genderize.io/ to predict the gender for the name "Jessie" in the US and the UK. Is there any difference?
You will have to submit two queries.
Hint: Look up the country codes in `our data`.
```{r}
```