-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAPI extract to Python
482 lines (298 loc) · 13.1 KB
/
API extract to Python
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
import sqlite3
import pandas as pd
import requests
from pyjstat import pyjstat
#Link to statistics Finland table
postUrl2019 = 'https://pxnet2.stat.fi:443/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/2021/paavo_pxt_12f3.px'
# Query used to return data from URL
apiQuery = {
"query": [
],
"response": {
"format": "json-stat2"
}
}
# Function to convert the extraction into 2 dataframes, takes 2 parameters
def apiToDataframe(postUrl2019, query):
# postUrl PostUrl where you you want the query posted
res = requests.post(postUrl2019, json=query)
# put the result in variable ds. Here you also have some metadata
ds = pyjstat.Dataset.read(res.text)
# write resultatet to 2 dataframes
# first dataframe with text
df = ds.write('dataframe')
# next dataframe with codes
df_id = ds.write('dataframe', naming='id')
# returner also ds if one need metadata
return df, df_id, ds
df, df_id, ds = apiToDataframe(postUrl2019, apiQuery)
df
df_id
ds
#Amend extracted data to only include currently needed information for tables
averageIncomeOnly = df[df['Information'].str.contains("Average")]
toDatabase = averageIncomeOnly[["Postal code area", "value"]]
toDatabase.rename(columns={'Postal code area': 'post_code_area', 'value' : 'value_2019'}, inplace=True)
toDatabase['post_code'] = toDatabase['post_code_area'].str[:5]
toDatabase = toDatabase[toDatabase.post_code != "WHOLE"]
#loading data into sqlite database
try:
sqliteConnection = sqlite3.connect('statisticsFinland.db')
con = sqliteConnection.cursor()
print("Database created and Successfully Connected to SQLite")
table_create = '''CREATE TABLE IF NOT EXISTS averageIncome2019 (post_code_area VARCHAR(255), value_2019 INT, post_code INT);'''
con.execute(table_create)
sqliteConnection.commit()
print("SQLite table created")
toDatabase.to_sql('averageIncome2019', sqliteConnection, if_exists='append', index=False)
except sqlite3.Error as error:
print("Error while connecting to sqlite", error)
finally:
if sqliteConnection:
sqliteConnection.close()
print("The SQLite connection is closed")
###############################################################################################################
postUrl2017 = 'https://pxnet2.stat.fi:443/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/2020/paavo_pxt_12f3.px'
# Query used to return data from URL
apiQuery = {
"query": [
],
"response": {
"format": "json-stat2"
}
}
# Function to convert the extraction into 2 dataframes, takes 2 parameters
def apiToDataframe(postUrl2017, query):
# postUrl PostUrl where you you want the query posted
res = requests.post(postUrl2017, json=query)
# put the result in variable ds. Here you also have some metadata
ds = pyjstat.Dataset.read(res.text)
# write resultatet to 2 dataframes
# first dataframe with text
df = ds.write('dataframe')
# next dataframe with codes
df_id = ds.write('dataframe', naming='id')
# returner also ds if one need metadata
return df, df_id, ds
df, df_id, ds = apiToDataframe(postUrl2017, apiQuery)
df
df_id
ds
#Amend extracted data to only include currently needed information for tables
averageIncomeOnly = df[df['Information'].str.contains("Average")]
toDatabase = averageIncomeOnly[["Postal code area", "value"]]
toDatabase.rename(columns={'Postal code area': 'post_code_area', 'value' : 'value_2017'}, inplace=True)
toDatabase['post_code'] = toDatabase['post_code_area'].str[:5]
toDatabase = toDatabase[toDatabase.post_code != "WHOLE"]
#loading data into sqlite database
try:
sqliteConnection = sqlite3.connect('statisticsFinland.db')
con = sqliteConnection.cursor()
print("Database created and Successfully Connected to SQLite")
table_create = '''CREATE TABLE IF NOT EXISTS averageIncome2017 (post_code_area VARCHAR(255), value_2017 INT, post_code INT);'''
con.execute(table_create)
sqliteConnection.commit()
print("SQLite table created")
toDatabase.to_sql('averageIncome2017', sqliteConnection, if_exists='append', index=False)
except sqlite3.Error as error:
print("Error while connecting to sqlite", error)
finally:
if sqliteConnection:
sqliteConnection.close()
print("The SQLite connection is closed")
#############################################################################################################################################
postUrl2016 = 'https://pxnet2.stat.fi:443/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/2019/paavo_5_tr_2019.px'
# Query used to return data from URL
apiQuery = {
"query": [
],
"response": {
"format": "json-stat2"
}
}
# Function to convert the extraction into 2 dataframes, takes 2 parameters
def apiToDataframe(postUrl2016, query):
# postUrl PostUrl where you you want the query posted
res = requests.post(postUrl2016, json=query)
# put the result in variable ds. Here you also have some metadata
ds = pyjstat.Dataset.read(res.text)
# write resultatet to 2 dataframes
# first dataframe with text
df = ds.write('dataframe')
# next dataframe with codes
df_id = ds.write('dataframe', naming='id')
# returner also ds if one need metadata
return df, df_id, ds
df, df_id, ds = apiToDataframe(postUrl2016, apiQuery)
df
df_id
ds
#Amend extracted data to only include currently needed information for tables
averageIncomeOnly = df[df['Data'].str.contains("Average")]
toDatabase = averageIncomeOnly[["Postal code area", "value"]]
toDatabase.rename(columns={'Postal code area': 'post_code_area', 'value' : 'value_2016'}, inplace=True)
toDatabase['post_code'] = toDatabase['post_code_area'].str[:5]
toDatabase = toDatabase[toDatabase.post_code != "Finla"]
#loading data into sqlite database
try:
sqliteConnection = sqlite3.connect('statisticsFinland.db')
con = sqliteConnection.cursor()
print("Database created and Successfully Connected to SQLite")
table_create = '''CREATE TABLE IF NOT EXISTS averageIncome2016 (post_code_area VARCHAR(255), value_2016 INT, post_code INT);'''
con.execute(table_create)
sqliteConnection.commit()
print("SQLite table created")
toDatabase.to_sql('averageIncome2016', sqliteConnection, if_exists='append', index=False)
except sqlite3.Error as error:
print("Error while connecting to sqlite", error)
finally:
if sqliteConnection:
sqliteConnection.close()
print("The SQLite connection is closed")
#############################################################################################################################################
postUrl2015 = 'https://pxnet2.stat.fi:443/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/2018/paavo_5_tr_2018.px'
# Query used to return data from URL
apiQuery = {
"query": [
],
"response": {
"format": "json-stat2"
}
}
# Function to convert the extraction into 2 dataframes, takes 2 parameters
def apiToDataframe(postUrl2015, query):
# postUrl PostUrl where you you want the query posted
res = requests.post(postUrl2015, json=query)
# put the result in variable ds. Here you also have some metadata
ds = pyjstat.Dataset.read(res.text)
# write resultatet to 2 dataframes
# first dataframe with text
df = ds.write('dataframe')
# next dataframe with codes
df_id = ds.write('dataframe', naming='id')
# returner also ds if one need metadata
return df, df_id, ds
df, df_id, ds = apiToDataframe(postUrl2015, apiQuery)
df
df_id
ds
#Amend extracted data to only include currently needed information for tables
averageIncomeOnly = df[df['Data'].str.contains("Average")]
toDatabase = averageIncomeOnly[["Postal code area", "value"]]
toDatabase.rename(columns={'Postal code area': 'post_code_area', 'value' : 'value_2015'}, inplace=True)
toDatabase['post_code'] = toDatabase['post_code_area'].str[:5]
toDatabase = toDatabase[toDatabase.post_code != "Finla"]
#loading data into sqlite database
try:
sqliteConnection = sqlite3.connect('statisticsFinland.db')
con = sqliteConnection.cursor()
print("Database created and Successfully Connected to SQLite")
table_create = '''CREATE TABLE IF NOT EXISTS averageIncome2015 (post_code_area VARCHAR(255), value_2015 INT, post_code INT);'''
con.execute(table_create)
sqliteConnection.commit()
print("SQLite table created")
toDatabase.to_sql('averageIncome2015', sqliteConnection, if_exists='append', index=False)
except sqlite3.Error as error:
print("Error while connecting to sqlite", error)
finally:
if sqliteConnection:
sqliteConnection.close()
print("The SQLite connection is closed")
#############################################################################################################################################
postUrl2014 = 'https://pxnet2.stat.fi:443/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/2017/paavo_5_tr_2017.px'
# Query used to return data from URL
apiQuery = {
"query": [
],
"response": {
"format": "json-stat2"
}
}
# Function to convert the extraction into 2 dataframes, takes 2 parameters
def apiToDataframe(postUrl2014, query):
# postUrl PostUrl where you you want the query posted
res = requests.post(postUrl2014, json=query)
# put the result in variable ds. Here you also have some metadata
ds = pyjstat.Dataset.read(res.text)
# write resultatet to 2 dataframes
# first dataframe with text
df = ds.write('dataframe')
# next dataframe with codes
df_id = ds.write('dataframe', naming='id')
# returner also ds if one need metadata
return df, df_id, ds
df, df_id, ds = apiToDataframe(postUrl2014, apiQuery)
df
df_id
ds
#Amend extracted data to only include currently needed information for tables
averageIncomeOnly = df[df['Data'].str.contains("Average")]
toDatabase = averageIncomeOnly[["Postal code area", "value"]]
toDatabase.rename(columns={'Postal code area': 'post_code_area', 'value' : 'value_2014'}, inplace=True)
toDatabase['post_code'] = toDatabase['post_code_area'].str[:5]
toDatabase = toDatabase[toDatabase.post_code != "Finla"]
#loading data into sqlite database
try:
sqliteConnection = sqlite3.connect('statisticsFinland.db')
con = sqliteConnection.cursor()
print("Database created and Successfully Connected to SQLite")
table_create = '''CREATE TABLE IF NOT EXISTS averageIncome2014 (post_code_area VARCHAR(255), value_2014 INT, post_code INT);'''
con.execute(table_create)
sqliteConnection.commit()
print("SQLite table created")
toDatabase.to_sql('averageIncome2014', sqliteConnection, if_exists='append', index=False)
except sqlite3.Error as error:
print("Error while connecting to sqlite", error)
finally:
if sqliteConnection:
sqliteConnection.close()
print("The SQLite connection is closed")
#############################################################################################################################################
postUrl2013 = 'https://pxnet2.stat.fi:443/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/2016/paavo_5_tr_2016.px'
# Query used to return data from URL
apiQuery = {
"query": [
],
"response": {
"format": "json-stat2"
}
}
# Function to convert the extraction into 2 dataframes, takes 2 parameters
def apiToDataframe(postUrl2013, query):
# postUrl PostUrl where you you want the query posted
res = requests.post(postUrl2013, json=query)
# put the result in variable ds. Here you also have some metadata
ds = pyjstat.Dataset.read(res.text)
# write resultatet to 2 dataframes
# first dataframe with text
df = ds.write('dataframe')
# next dataframe with codes
df_id = ds.write('dataframe', naming='id')
# returner also ds if one need metadata
return df, df_id, ds
df, df_id, ds = apiToDataframe(postUrl2013, apiQuery)
df
df_id
ds
#Amend extracted data to only include currently needed information for tables
averageIncomeOnly = df[df['Data'].str.contains("Average")]
toDatabase = averageIncomeOnly[["Postal code area", "value"]]
toDatabase.rename(columns={'Postal code area': 'post_code_area', 'value' : 'value_2013'}, inplace=True)
toDatabase['post_code'] = toDatabase['post_code_area'].str[:5]
toDatabase = toDatabase[toDatabase.post_code != "Finla"]
#loading data into sqlite database
try:
sqliteConnection = sqlite3.connect('statisticsFinland.db')
con = sqliteConnection.cursor()
print("Database created and Successfully Connected to SQLite")
table_create = '''CREATE TABLE IF NOT EXISTS averageIncome2013 (post_code_area VARCHAR(255), value_2013 INT, post_code INT);'''
con.execute(table_create)
sqliteConnection.commit()
print("SQLite table created")
toDatabase.to_sql('averageIncome2013', sqliteConnection, if_exists='append', index=False)
except sqlite3.Error as error:
print("Error while connecting to sqlite", error)
finally:
if sqliteConnection:
sqliteConnection.close()
print("The SQLite connection is closed")