ebird-api-requests 4.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,110 @@
1
+ """Functions for fetching information about regions."""
2
+
3
+ from ebird.api.requests.utils import call
4
+ from ebird.api.requests.validation import clean_region, clean_region_type
5
+
6
+ REGION_LIST_URL = "https://api.ebird.org/v2/ref/region/list/%s/%s"
7
+ ADJACENT_REGIONS_URL = "https://api.ebird.org/v2/ref/adjacent/%s"
8
+ REGION_INFO_URL = "https://api.ebird.org/v2/ref/region/info/%s"
9
+
10
+
11
+ def get_regions(token, rtype, region):
12
+ """Get the list of sub-regions or a given region.
13
+
14
+ This maps to the end point in the eBird API 2.0,
15
+ https://documenter.getpostman.com/view/664302/S1ENwy59?version=latest#e25218db-566b-4d8b-81ca-e79a8f68c599
16
+
17
+ Not all combinations of region type and region code are supported.
18
+ You can get all the subnational2 regions of a country but you cannot
19
+ get the subnational2 regions for the world.
20
+
21
+ :param token: the token needed to access the API.
22
+
23
+ :param rtype: the region type, either 'country', 'subnational1'
24
+ or 'subnational2'.
25
+
26
+ :param region: the name of the region, either 'world', a country or
27
+ a subnational1 code.
28
+
29
+ :return: the list of sub-regions within the given region.
30
+
31
+ :raises ValueError: if an invalid region type is given.
32
+
33
+ :raises URLError if there is an error with the connection to the
34
+ eBird site.
35
+
36
+ :raises HTTPError if the eBird API returns an error.
37
+
38
+ """
39
+ url = REGION_LIST_URL % (clean_region_type(rtype), clean_region(region))
40
+
41
+ headers = {
42
+ "X-eBirdApiToken": token,
43
+ }
44
+
45
+ return call(url, {}, headers)
46
+
47
+
48
+ def get_adjacent_regions(token, region):
49
+ """Get the regions adjacent to a given region.
50
+
51
+ This maps to the end point in the eBird API 2.0,
52
+ https://documenter.getpostman.com/view/664302/S1ENwy59?version=latest#3aca0519-3105-47fc-8611-a4dfd500a32f
53
+
54
+ :param token: the token needed to access the API.
55
+
56
+ :param region: the name of the region, either a country, a subnational1
57
+ or a subnational2 code.
58
+
59
+ :return: the list of regions bordering the specified region.
60
+
61
+ :raises ValueError: if an invalid region code.
62
+
63
+ :raises URLError if there is an error with the connection to the
64
+ eBird site.
65
+
66
+ :raises HTTPError if the eBird API returns an error.
67
+
68
+ """
69
+ url = ADJACENT_REGIONS_URL % clean_region(region)
70
+
71
+ headers = {
72
+ "X-eBirdApiToken": token,
73
+ }
74
+
75
+ return call(url, {}, headers)
76
+
77
+
78
+ def get_region(token, region):
79
+ """Get the geographical details of a country, region or sub-region.
80
+
81
+ This maps to the end point in the eBird API 2.0,
82
+ https://documenter.getpostman.com/view/664302/S1ENwy59?version=latest#e25218db-566b-4d8b-81ca-e79a8f68c599
83
+
84
+ There are two query parameters supported by the API, regionNameFormat
85
+ and delim. These are used to control how the name of the region that the
86
+ region code corresponds to is presented, e.g. US-NY returns "New York,
87
+ United States". The utility of these is rather limited so they are
88
+ currently not supported.
89
+
90
+ :param token: the token needed to access the API.
91
+
92
+ :param region: the code for the region, eg. US-NV.
93
+
94
+ :return: the latitude, longitude, name, region, etc. for the area.
95
+
96
+ :raises ValueError: if an invalid region code is given.
97
+
98
+ :raises URLError if there is an error with the connection to the
99
+ eBird site.
100
+
101
+ :raises HTTPError if the eBird API returns an error.
102
+
103
+ """
104
+ url = REGION_INFO_URL % clean_region(region)
105
+
106
+ headers = {
107
+ "X-eBirdApiToken": token,
108
+ }
109
+
110
+ return call(url, {}, headers)
@@ -0,0 +1,37 @@
1
+ """Functions for fetching information about species."""
2
+
3
+ from ebird.api.requests.utils import call
4
+ from ebird.api.requests.validation import clean_area
5
+
6
+ SPECIES_LIST_URL = "https://api.ebird.org/v2/product/spplist/%s"
7
+
8
+
9
+ def get_species_list(token, area):
10
+ """
11
+ Get the list of species for an area.
12
+
13
+ The maps to the two end points in the eBird API 2.0,
14
+ https://documenter.getpostman.com/view/664302/S1ENwy59?version=latest#55bd1b26-6951-4a88-943a-d3a8aa1157dd
15
+
16
+ :param token: the token needed to access the API.
17
+
18
+ :param area: the code for a country, subnational1 region, subnational2
19
+ region or location.
20
+
21
+ :return: codes, e.g. horlar1, for the list of species observed in the area.
22
+
23
+ :raises ValueError: if any of the arguments fail the validation checks.
24
+
25
+ :raises URLError if there is an error with the connection to the
26
+ eBird site.
27
+
28
+ :raises HTTPError if the eBird API returns an error.
29
+
30
+ """
31
+ url = SPECIES_LIST_URL % clean_area(area)
32
+
33
+ headers = {
34
+ "X-eBirdApiToken": token,
35
+ }
36
+
37
+ return call(url, {}, headers)
@@ -0,0 +1,90 @@
1
+ """Functions for fetching basic statistics about observers and observations."""
2
+
3
+ from ebird.api.requests.utils import call
4
+ from ebird.api.requests.validation import (
5
+ clean_area,
6
+ clean_date,
7
+ clean_max_observers,
8
+ clean_rank,
9
+ clean_region,
10
+ )
11
+
12
+ TOP_100_URL = "https://api.ebird.org/v2/product/top100/%s/%s"
13
+ TOTALS_URL = "https://api.ebird.org/v2/product/stats/%s/%s"
14
+
15
+
16
+ def get_top_100(token, region, date, rank="spp", max_results=100):
17
+ """
18
+ Get the observers who have seen the most species or submitted the
19
+ greatest number of checklists on a given date.
20
+
21
+ The maps to the end point in the eBird API 2.0,
22
+ https://documenter.getpostman.com/view/664302/S1ENwy59?version=latest#2d8d3f94-c4b0-42bd-9c8e-71edfa6347ba
23
+
24
+ :param token: the token needed to access the API.
25
+
26
+ :param region: the code for the region, eg. US-NV.
27
+
28
+ :param date: the date, since Jan 1st 1800.
29
+
30
+ :param rank: order results by species seen (spp) or checklists submitted (cl).
31
+
32
+ :param max_results: the maximum number of entries to return from
33
+ 1 to 100. The default value is 100.
34
+
35
+ :return: the list of observers.
36
+
37
+ :raises ValueError: if any of the arguments fail the validation checks.
38
+
39
+ :raises URLError if there is an error with the connection to the
40
+ eBird site.
41
+
42
+ :raises HTTPError if the eBird API returns an error.
43
+
44
+ """
45
+ url = TOP_100_URL % (clean_region(region), date.strftime("%Y/%m/%d"))
46
+
47
+ params = {
48
+ "maxObservers": clean_max_observers(max_results),
49
+ "rankedBy": clean_rank(rank),
50
+ }
51
+
52
+ headers = {
53
+ "X-eBirdApiToken": token,
54
+ }
55
+
56
+ return call(url, params, headers)
57
+
58
+
59
+ def get_totals(token, area, date):
60
+ """
61
+ Get the number of contributors, checklists submitted and species seen
62
+ on a given date.
63
+
64
+ The maps to the end point in the eBird API 2.0,
65
+ https://documenter.getpostman.com/view/664302/S1ENwy59?version=latest#4416a7cc-623b-4340-ab01-80c599ede73e
66
+
67
+ :param token: the token needed to access the API.
68
+
69
+ :param area: the code for a country subnational1 , subnational2 region
70
+ or location
71
+
72
+ :param date: the date, since Jan 1st 1800.
73
+
74
+ :return: the totals for the given date
75
+
76
+ :raises ValueError: if any of the arguments fail the validation checks.
77
+
78
+ :raises URLError if there is an error with the connection to the
79
+ eBird site.
80
+
81
+ :raises HTTPError if the eBird API returns an error.
82
+
83
+ """
84
+ url = TOTALS_URL % (clean_area(area), clean_date(date))
85
+
86
+ headers = {
87
+ "X-eBirdApiToken": token,
88
+ }
89
+
90
+ return call(url, {}, headers)
@@ -0,0 +1,213 @@
1
+ """Functions for fetching information about the taxonomy used by eBird."""
2
+
3
+ from ebird.api.requests.utils import call
4
+ from ebird.api.requests.validation import (
5
+ clean_categories,
6
+ clean_codes,
7
+ clean_locale,
8
+ clean_ordering,
9
+ clean_species_code,
10
+ )
11
+
12
+ TAXONOMY_URL = "https://api.ebird.org/v2/ref/taxonomy/ebird"
13
+ TAXONOMY_FORMS_URL = "https://api.ebird.org/v2/ref/taxon/forms/%s"
14
+ TAXONOMY_GROUPS_URL = "https://api.ebird.org/v2/ref/sppgroup/%s"
15
+ TAXONOMY_VERSIONS_URL = "https://api.ebird.org/v2/ref/taxonomy/versions"
16
+ TAXONOMY_LOCALES_URL = "https://api.ebird.org/v2/ref/taxa-locales/ebird"
17
+
18
+
19
+ def get_taxonomy(token, category=None, locale="en", version=None, species=None):
20
+ """Get the full or specific subset of the taxonomy used by eBird.
21
+
22
+ The maps to the end point in the eBird API 2.0,
23
+ https://documenter.getpostman.com/view/664302/S1ENwy59?version=latest#952a4310-536d-4ad1-8f3e-77cfb624d1bc
24
+
25
+ :param token: the token needed to access the API.
26
+
27
+ :param category: one or more categories of species to return: 'domestic',
28
+ 'form', 'hybrid', 'intergrade', 'issf', 'slash', 'species' or 'spuh'.
29
+ More than one value can be given in a comma-separated string.
30
+
31
+ :param locale: the language (to use) for the species common names. The
32
+ default of 'en' will use species names from the eBird/Clements checklist.
33
+ This can be any locale for which eBird has translations available. For a
34
+ complete list see, http://help.ebird.org/customer/portal/articles/1596582.
35
+
36
+ :param version: the version number of the taxonomy to return,
37
+ see get_taxonomy_versions()
38
+
39
+ :param species: a comma-separate string or list containing scientific
40
+ names or 6-letter species codes.
41
+
42
+ :return: the list of entries matching the category.
43
+
44
+ :raises ValueError: if an invalid category or locale is given.
45
+
46
+ :raises ValueError: if both a category and species are used. In this case
47
+ the eBird API ignore the species and returns only results for the category.
48
+
49
+ :raises URLError if there is an error with the connection to the
50
+ eBird site.
51
+
52
+ :raises HTTPError if the eBird API returns an error.
53
+
54
+ """
55
+ params = {"locale": clean_locale(locale), "fmt": "json"}
56
+
57
+ if category is not None:
58
+ params["cat"] = ",".join(clean_categories(category))
59
+
60
+ if version is not None:
61
+ params["version"] = version
62
+
63
+ if species is not None:
64
+ params["species"] = ",".join(clean_codes(species))
65
+
66
+ headers = {
67
+ "X-eBirdApiToken": token,
68
+ }
69
+
70
+ return call(TAXONOMY_URL, params, headers)
71
+
72
+
73
+ def get_taxonomy_forms(token, species):
74
+ """Get all the sub-specific forms of a given species.
75
+
76
+ The maps to the end point in the eBird API 2.0,
77
+ https://documenter.getpostman.com/view/664302/S1ENwy59?version=latest#e338e5a6-919d-4603-a7db-6c690fa62371
78
+
79
+ NOTE: the get_taxonomy() API call returns 6-letter species codes.
80
+
81
+ :param token: the token needed to access the API.
82
+
83
+ :param species: the 6-letter eBird species code, e.g. horlar (Horned Lark).
84
+
85
+ :return: the list of codes of each sub-species.
86
+
87
+ :raises ValueError is the species code is invalid (not 6 letters).
88
+
89
+ :raises URLError if there is an error with the connection to the
90
+ eBird site.
91
+
92
+ :raises HTTPError if the eBird API returns an error.
93
+
94
+ """
95
+ url = TAXONOMY_FORMS_URL % clean_species_code(species)
96
+
97
+ headers = {
98
+ "X-eBirdApiToken": token,
99
+ }
100
+
101
+ return call(url, {}, headers)
102
+
103
+
104
+ def get_taxonomy_groups(token, ordering="ebird", locale="en"):
105
+ """Get the names of the groups of species used in the taxonomy.
106
+
107
+ The maps to the end point in the eBird API 2.0,
108
+ https://documenter.getpostman.com/view/664302/S1ENwy59?version=latest#aa9804aa-dbf9-4a53-bbf4-48e214e4677a
109
+
110
+ NOTE: Not all the locales supported by the eBird site or apps
111
+ are available in the API. The following locales are not
112
+ supported, (language, locale code):
113
+
114
+ Croatian, hr
115
+ Croatian, hr
116
+ Faroese, fo
117
+ Finnish, fi
118
+ Haitian, ht_HT
119
+ Hungarian, hu
120
+ Indonesian, id
121
+ Italian, it
122
+ Japanese, ja
123
+ Korean, ko
124
+ Latvian, lv
125
+ Lithuanian, lt
126
+ Malayalam, ml
127
+ Mongolian, mn
128
+ Polish, pl
129
+ Slovenian, sl
130
+ Swedish, sv
131
+ Ukrainian, uk
132
+
133
+ :param token: the token needed to access the API.
134
+
135
+ :param ordering: order groups using taxonomic order, 'ebird' or by
136
+ likeness, 'merlin'.
137
+
138
+ :param locale: the language (to use) for the group names.
139
+
140
+ :return: the list of species groups.
141
+
142
+ :raises ValueError: if an invalid ordering or locale is given.
143
+
144
+ :raises URLError if there is an error with the connection to the
145
+ eBird site.
146
+
147
+ :raises HTTPError if the eBird API returns an error.
148
+
149
+ """
150
+ url = TAXONOMY_GROUPS_URL % clean_ordering(ordering)
151
+
152
+ params = {
153
+ "groupNameLocale": clean_locale(locale),
154
+ }
155
+
156
+ headers = {
157
+ "X-eBirdApiToken": token,
158
+ }
159
+
160
+ return call(url, params, headers)
161
+
162
+
163
+ def get_taxonomy_versions(token):
164
+ """Get all versions of the taxonomy, indicating which is the latest.
165
+
166
+ The maps to the end point in the eBird API 2.0,
167
+ https://documenter.getpostman.com/view/664302/S1ENwy59?version=latest#9bba1ff5-6eb2-4f9a-91fd-e5ed34e51500
168
+
169
+ :param token: the token needed to access the API.
170
+
171
+ :return: a list of all the taxonomy versions used by eBird.
172
+
173
+ :raises URLError if there is an error with the connection to the
174
+ eBird site.
175
+
176
+ :raises HTTPError if the eBird API returns an error.
177
+
178
+ """
179
+ headers = {
180
+ "X-eBirdApiToken": token,
181
+ }
182
+
183
+ return call(TAXONOMY_VERSIONS_URL, {}, headers)
184
+
185
+
186
+ def get_taxonomy_locales(token):
187
+ """Get all locales supported for common names.
188
+
189
+ The maps to the end point in the eBird API 2.0,
190
+ https://documenter.getpostman.com/view/664302/S1ENwy59?version=latest#3ea8ff71-c254-4811-9e80-b445a39302a6
191
+
192
+ This API call returns a list of all the languages supported
193
+ by eBird. An entry in the list takes the form:
194
+
195
+ {'code': 'af', 'lastUpdate': '2024-12-21 06:06', 'name': 'Afrikaans'}
196
+
197
+ There are currently, (2024-12-30), 107 languages available.
198
+
199
+ :param token: the token needed to access the API.
200
+
201
+ :return: a list of all the taxonomy locales used by eBird.
202
+
203
+ :raises URLError if there is an error with the connection to the
204
+ eBird site.
205
+
206
+ :raises HTTPError if the eBird API returns an error.
207
+
208
+ """
209
+ headers = {
210
+ "X-eBirdApiToken": token,
211
+ }
212
+
213
+ return call(TAXONOMY_LOCALES_URL, {}, headers)
@@ -0,0 +1,164 @@
1
+ """Various functions used in the API."""
2
+
3
+ import json
4
+ from urllib.parse import urlencode
5
+ from urllib.request import Request, urlopen
6
+
7
+ from ebird.api.requests import constants
8
+
9
+ _parameter_defaults = {
10
+ "back": constants.DEFAULT_BACK,
11
+ "cat": constants.DEFAULT_SPECIES_CATEGORY,
12
+ "detail": constants.DEFAULT_DETAIL,
13
+ "dist": constants.DEFAULT_DISTANCE,
14
+ "groupNameLocale": constants.DEFAULT_LOCALE,
15
+ "hotspot": constants.DEFAULT_HOTSPOTS_ONLY,
16
+ "includeProvisional": constants.DEFAULT_PROVISIONAL,
17
+ "sort": constants.DEFAULT_OBSERVATION_ORDER,
18
+ "locale": constants.DEFAULT_LOCALE,
19
+ "sppLocale": constants.DEFAULT_LOCALE,
20
+ "maxObservations": constants.DEFAULT_MAX_OBSERVATIONS,
21
+ "maxObservers": constants.DEFAULT_MAX_OBSERVERS,
22
+ "maxVisits": constants.DEFAULT_MAX_CHECKLISTS,
23
+ "rankedBy": constants.DEFAULT_TOP_100_RANK,
24
+ }
25
+
26
+ _parameter_map = {
27
+ "maxObservations": "maxResults",
28
+ "maxObservers": "maxResults",
29
+ "maxVisits": "maxResults",
30
+ }
31
+
32
+
33
+ def map_parameters(params):
34
+ """Translate the names of the query parameters to match those used
35
+ in the API.
36
+
37
+ :param params: a dict contains the GET parameters for the request that
38
+ will be sent to the eBird API.
39
+
40
+ :return: a copy of the params dictionary with only the parameters
41
+ that are not set to a default value.
42
+
43
+ """
44
+ mapped = {}
45
+
46
+ for key, value in params.items():
47
+ key = _parameter_map.get(key, key)
48
+ mapped[key] = value
49
+
50
+ return mapped
51
+
52
+
53
+ def filter_parameters(params):
54
+ """Filter out any parameter which matches the eBird API default value.
55
+
56
+ :param params: a dict contains the GET parameters for the request that
57
+ will be sent to the eBird API.
58
+
59
+ :return: a copy of the params dictionary with only the parameters
60
+ that are not set to a default value.
61
+
62
+ """
63
+ filtered = {}
64
+
65
+ defaults = _parameter_defaults.copy()
66
+
67
+ for key, value in params.items():
68
+ if key in defaults:
69
+ if value != defaults[key]:
70
+ filtered[key] = value
71
+ else:
72
+ filtered[key] = value
73
+
74
+ return filtered
75
+
76
+
77
+ def get_response(url, params=None, headers=None):
78
+ """Get the content from the eBird API.
79
+
80
+ :param url: the URL for the API call.
81
+ :type url: str
82
+
83
+ :param params: the query parameters for the API call.
84
+ :type params: dict
85
+
86
+ :param headers: the headers to add to the request.
87
+ :type params: dict
88
+
89
+ :return: the content returned by the API
90
+ :rtype: str
91
+
92
+ :raises URLError if there is an error with the connection to the
93
+ eBird site.
94
+
95
+ :raises HTTPError if the eBird API returns an error.
96
+
97
+ """
98
+ if params:
99
+ url += "?" + urlencode(params, doseq=True)
100
+
101
+ request = Request(url)
102
+
103
+ if headers:
104
+ for name, value in headers.items():
105
+ request.add_header(name, value)
106
+
107
+ return urlopen(request).read()
108
+
109
+
110
+ def get_json(content):
111
+ """Decode the JSON records from the response.
112
+
113
+ :param content: the content returned by the eBird API.
114
+ :type content: http.client.HTTPResponse:
115
+
116
+ :return: the records decoded from the JSON payload.
117
+ :rtype: list
118
+
119
+ """
120
+ return json.loads(content.decode("utf-8"))
121
+
122
+
123
+ def save_json(filename, data, indent=None):
124
+ """Save results to a file.
125
+
126
+ :param filename: the name of the file to save. The .json
127
+ extension will be added if not present.
128
+
129
+ :param data: the list of records to save.
130
+
131
+ :param indent: whether to pretty-print results by adding indentation
132
+ for each level. The default is no formatting.
133
+
134
+ """
135
+ if not filename.endswith(".json"):
136
+ filename += ".json"
137
+ with open(filename, "w") as outfile:
138
+ json.dump(data, outfile, indent=indent)
139
+
140
+
141
+ def call(url, params, headers):
142
+ """Call the eBird API.
143
+
144
+ :param url: the URL for the API call.
145
+ :type url: str
146
+
147
+ :param params: the query parameters for the API call.
148
+ :type params: dict
149
+
150
+ :param headers: the headers to add to the request.
151
+ :type params: dict
152
+
153
+ :return: the content returned by the API
154
+ :rtype: dict | list
155
+
156
+ :raises URLError if there is an error with the connection to the
157
+ eBird site.
158
+
159
+ :raises HTTPError if the eBird API returns an error.
160
+
161
+ """
162
+ filtered = filter_parameters(params)
163
+ mapped = map_parameters(filtered)
164
+ return get_json(get_response(url, mapped, headers))