pxwebpy 0.1.1__tar.gz → 0.2.0__tar.gz
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.
- pxwebpy-0.2.0/.github/workflows/ci.yml +39 -0
- pxwebpy-0.2.0/.github/workflows/release.yml +28 -0
- pxwebpy-0.2.0/.gitignore +6 -0
- pxwebpy-0.2.0/.python-version +1 -0
- pxwebpy-0.2.0/PKG-INFO +83 -0
- pxwebpy-0.2.0/README.md +64 -0
- pxwebpy-0.2.0/examples/example.py +84 -0
- pxwebpy-0.2.0/examples/example_query.json +45 -0
- pxwebpy-0.2.0/pyproject.toml +49 -0
- pxwebpy-0.2.0/requirements-dev.lock +29 -0
- pxwebpy-0.2.0/requirements.lock +15 -0
- {pxwebpy-0.1.1 → pxwebpy-0.2.0/src}/pxwebpy/__init__.py +1 -1
- pxwebpy-0.2.0/src/pxwebpy/pxwebpy.py +193 -0
- pxwebpy-0.2.0/tests/invalid_query.json +12 -0
- pxwebpy-0.2.0/tests/mock/response_fi.json +233 -0
- pxwebpy-0.2.0/tests/mock/response_gl.json +271 -0
- pxwebpy-0.2.0/tests/mock/response_no.json +506 -0
- pxwebpy-0.2.0/tests/mock/result_fi.json +632 -0
- pxwebpy-0.2.0/tests/mock/result_gl.json +866 -0
- pxwebpy-0.2.0/tests/mock/result_no.json +2018 -0
- pxwebpy-0.2.0/tests/queries.json +182 -0
- pxwebpy-0.2.0/tests/test_pxweb.py +125 -0
- pxwebpy-0.2.0/tests/valid_query.json +45 -0
- pxwebpy-0.1.1/PKG-INFO +0 -38
- pxwebpy-0.1.1/README.md +0 -24
- pxwebpy-0.1.1/pxwebpy/pxwebpy.py +0 -163
- pxwebpy-0.1.1/pyproject.toml +0 -24
- {pxwebpy-0.1.1 → pxwebpy-0.2.0}/LICENSE +0 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
name: ci
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [ "main" ]
|
|
6
|
+
pull_request:
|
|
7
|
+
branches: [ "main" ]
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
build:
|
|
11
|
+
|
|
12
|
+
runs-on: ubuntu-latest
|
|
13
|
+
strategy:
|
|
14
|
+
fail-fast: false
|
|
15
|
+
matrix:
|
|
16
|
+
python-version: ["3.11", "3.12"]
|
|
17
|
+
|
|
18
|
+
steps:
|
|
19
|
+
- uses: actions/checkout@v4
|
|
20
|
+
|
|
21
|
+
- name: Install and setup rye
|
|
22
|
+
run: |
|
|
23
|
+
curl -sSf https://rye-up.com/get | RYE_VERSION="0.22.0" RYE_TOOLCHAIN_VERSION="${{ matrix.python-version }}" RYE_INSTALL_OPTION="--yes" bash
|
|
24
|
+
echo "$HOME/.rye/shims" >> $GITHUB_PATH
|
|
25
|
+
|
|
26
|
+
- name: Pin ${{ matrix.python-version }}
|
|
27
|
+
run: |
|
|
28
|
+
rye pin ${{ matrix.python-version }}
|
|
29
|
+
|
|
30
|
+
- name: Run tests and lint
|
|
31
|
+
run: |
|
|
32
|
+
rye lock --features ci
|
|
33
|
+
rye sync --no-lock --no-dev
|
|
34
|
+
rye run pytest
|
|
35
|
+
rye lint
|
|
36
|
+
|
|
37
|
+
- name: Build
|
|
38
|
+
run: |
|
|
39
|
+
rye build
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
name: release
|
|
2
|
+
on:
|
|
3
|
+
release:
|
|
4
|
+
types: [published]
|
|
5
|
+
|
|
6
|
+
jobs:
|
|
7
|
+
build-release:
|
|
8
|
+
|
|
9
|
+
runs-on: ubuntu-latest
|
|
10
|
+
strategy:
|
|
11
|
+
fail-fast: false
|
|
12
|
+
|
|
13
|
+
steps:
|
|
14
|
+
- uses: actions/checkout@v4
|
|
15
|
+
|
|
16
|
+
- name: Install and setup rye
|
|
17
|
+
run: |
|
|
18
|
+
python_version=$(cat .python-version)
|
|
19
|
+
curl -sSf https://rye-up.com/get | RYE_VERSION="0.22.0" RYE_TOOLCHAIN_VERSION="$python_version" RYE_INSTALL_OPTION="--yes" bash
|
|
20
|
+
echo "$HOME/.rye/shims" >> $GITHUB_PATH
|
|
21
|
+
|
|
22
|
+
- name: Build for distribution
|
|
23
|
+
run: |
|
|
24
|
+
rye build
|
|
25
|
+
|
|
26
|
+
- name: Publish to PyPI
|
|
27
|
+
run: |
|
|
28
|
+
rye publish --token ${{ secrets.PYPI_TOKEN }} --yes
|
pxwebpy-0.2.0/.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
3.12
|
pxwebpy-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: pxwebpy
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Get data from PxWeb API easily.
|
|
5
|
+
Project-URL: Issue tracker, https://github.com/stefur/pxwebpy/issues
|
|
6
|
+
Author-email: stefur <stefan@furne.net>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: dataframes,pandas,polars,pxweb,statistics
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Requires-Python: >=3.11
|
|
15
|
+
Requires-Dist: requests>=2.31.0
|
|
16
|
+
Provides-Extra: ci
|
|
17
|
+
Requires-Dist: pytest>=8.0.0; extra == 'ci'
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# pxwebpy
|
|
21
|
+
[](https://github.com/stefur/pxwebpy/actions/workflows/ci.yml)
|
|
22
|
+

|
|
23
|
+

|
|
24
|
+
[](https://rye-up.com)
|
|
25
|
+
[](https://github.com/astral-sh/ruff)
|
|
26
|
+
Easily get data from the PxWeb API and into either a polars or pandas dataframe.
|
|
27
|
+
|
|
28
|
+
Pxwebpy parses the PxWeb table data as well as metadata using the json-stat2 response format.
|
|
29
|
+
|
|
30
|
+
It has been tested with [Statistics Sweden](https://scb.se), [Statistics Finland](https://www.stat.fi), [Statistics Greenland](https://stat.gl) and [Statistics Norway](https://www.ssb.no).
|
|
31
|
+
|
|
32
|
+
## Example usage
|
|
33
|
+
```python
|
|
34
|
+
>>> from pxwebpy import PxWeb
|
|
35
|
+
>>> import pandas as pd
|
|
36
|
+
|
|
37
|
+
>>> URL = "https://api.scb.se/OV0104/v1/doris/sv/ssd/START/HE/HE0110/HE0110A/SamForvInk1"
|
|
38
|
+
|
|
39
|
+
>>> QUERY = {
|
|
40
|
+
"query": [
|
|
41
|
+
{
|
|
42
|
+
"code": "Tid",
|
|
43
|
+
"selection": {
|
|
44
|
+
"filter": "item",
|
|
45
|
+
"values": [
|
|
46
|
+
"2021"
|
|
47
|
+
]
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
],
|
|
51
|
+
"response": {
|
|
52
|
+
"format": "json-stat2"
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
>>> tbl = PxWeb(URL, QUERY)
|
|
57
|
+
>>> print(tbl)
|
|
58
|
+
|
|
59
|
+
PxWeb(url='https://api.scb.se/OV0104/v1/doris/sv/ssd/START/HE/HE0110/HE0110A/SamForvInk1',
|
|
60
|
+
query={'query': [{'code': 'Tid', 'selection': {'filter': 'item', 'values': ['2021']}}], 'response': {'format': 'json-stat2'}},
|
|
61
|
+
metadata={'label': 'Sammanräknad förvärvsinkomst för boende i Sverige hela året efter ålder, tabellinnehåll och år', 'source': 'SCB', 'updated': '2023-01-10T10:42:00Z'},
|
|
62
|
+
last_refresh=2023-10-29 14:21:57.628639,
|
|
63
|
+
dataset=[{'ålder': 'totalt 16+ år', 'tabellinnehåll': 'Medelinkomst, tkr', 'år': '2021' ...
|
|
64
|
+
|
|
65
|
+
>>> df = pd.DataFrame(tbl.dataset)
|
|
66
|
+
>>> print(df)
|
|
67
|
+
ålder tabellinnehåll år value
|
|
68
|
+
0 totalt 16+ år Medelinkomst, tkr 2021 331.5
|
|
69
|
+
1 totalt 16+ år Medianinkomst, tkr 2021 301.5
|
|
70
|
+
2 totalt 16+ år Totalsumma, mnkr 2021 2779588.9
|
|
71
|
+
3 totalt 16+ år Antal personer 2021 8383640.0
|
|
72
|
+
4 16-19 år Medelinkomst, tkr 2021 28.1
|
|
73
|
+
.. ... ... ... ...
|
|
74
|
+
71 80-84 år Antal personer 2021 290684.0
|
|
75
|
+
72 85+ år Medelinkomst, tkr 2021 214.4
|
|
76
|
+
73 85+ år Medianinkomst, tkr 2021 200.1
|
|
77
|
+
74 85+ år Totalsumma, mnkr 2021 57529.3
|
|
78
|
+
75 85+ år Antal personer 2021 268320.0
|
|
79
|
+
|
|
80
|
+
[76 rows x 4 columns]
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
See [examples](examples/example.py) for more details on how to use pxwebpy.
|
pxwebpy-0.2.0/README.md
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# pxwebpy
|
|
2
|
+
[](https://github.com/stefur/pxwebpy/actions/workflows/ci.yml)
|
|
3
|
+

|
|
4
|
+

|
|
5
|
+
[](https://rye-up.com)
|
|
6
|
+
[](https://github.com/astral-sh/ruff)
|
|
7
|
+
Easily get data from the PxWeb API and into either a polars or pandas dataframe.
|
|
8
|
+
|
|
9
|
+
Pxwebpy parses the PxWeb table data as well as metadata using the json-stat2 response format.
|
|
10
|
+
|
|
11
|
+
It has been tested with [Statistics Sweden](https://scb.se), [Statistics Finland](https://www.stat.fi), [Statistics Greenland](https://stat.gl) and [Statistics Norway](https://www.ssb.no).
|
|
12
|
+
|
|
13
|
+
## Example usage
|
|
14
|
+
```python
|
|
15
|
+
>>> from pxwebpy import PxWeb
|
|
16
|
+
>>> import pandas as pd
|
|
17
|
+
|
|
18
|
+
>>> URL = "https://api.scb.se/OV0104/v1/doris/sv/ssd/START/HE/HE0110/HE0110A/SamForvInk1"
|
|
19
|
+
|
|
20
|
+
>>> QUERY = {
|
|
21
|
+
"query": [
|
|
22
|
+
{
|
|
23
|
+
"code": "Tid",
|
|
24
|
+
"selection": {
|
|
25
|
+
"filter": "item",
|
|
26
|
+
"values": [
|
|
27
|
+
"2021"
|
|
28
|
+
]
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
],
|
|
32
|
+
"response": {
|
|
33
|
+
"format": "json-stat2"
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
>>> tbl = PxWeb(URL, QUERY)
|
|
38
|
+
>>> print(tbl)
|
|
39
|
+
|
|
40
|
+
PxWeb(url='https://api.scb.se/OV0104/v1/doris/sv/ssd/START/HE/HE0110/HE0110A/SamForvInk1',
|
|
41
|
+
query={'query': [{'code': 'Tid', 'selection': {'filter': 'item', 'values': ['2021']}}], 'response': {'format': 'json-stat2'}},
|
|
42
|
+
metadata={'label': 'Sammanräknad förvärvsinkomst för boende i Sverige hela året efter ålder, tabellinnehåll och år', 'source': 'SCB', 'updated': '2023-01-10T10:42:00Z'},
|
|
43
|
+
last_refresh=2023-10-29 14:21:57.628639,
|
|
44
|
+
dataset=[{'ålder': 'totalt 16+ år', 'tabellinnehåll': 'Medelinkomst, tkr', 'år': '2021' ...
|
|
45
|
+
|
|
46
|
+
>>> df = pd.DataFrame(tbl.dataset)
|
|
47
|
+
>>> print(df)
|
|
48
|
+
ålder tabellinnehåll år value
|
|
49
|
+
0 totalt 16+ år Medelinkomst, tkr 2021 331.5
|
|
50
|
+
1 totalt 16+ år Medianinkomst, tkr 2021 301.5
|
|
51
|
+
2 totalt 16+ år Totalsumma, mnkr 2021 2779588.9
|
|
52
|
+
3 totalt 16+ år Antal personer 2021 8383640.0
|
|
53
|
+
4 16-19 år Medelinkomst, tkr 2021 28.1
|
|
54
|
+
.. ... ... ... ...
|
|
55
|
+
71 80-84 år Antal personer 2021 290684.0
|
|
56
|
+
72 85+ år Medelinkomst, tkr 2021 214.4
|
|
57
|
+
73 85+ år Medianinkomst, tkr 2021 200.1
|
|
58
|
+
74 85+ år Totalsumma, mnkr 2021 57529.3
|
|
59
|
+
75 85+ år Antal personer 2021 268320.0
|
|
60
|
+
|
|
61
|
+
[76 rows x 4 columns]
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
See [examples](examples/example.py) for more details on how to use pxwebpy.
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""pxwebpy pulling some data to Pandas and Polars respectively"""
|
|
2
|
+
|
|
3
|
+
import pandas as pd
|
|
4
|
+
import polars as pl # type: ignore
|
|
5
|
+
from pxwebpy import PxWeb
|
|
6
|
+
|
|
7
|
+
URL = "https://api.scb.se/OV0104/v1/doris/sv/ssd/START/HE/HE0110/HE0110A/SamForvInk1"
|
|
8
|
+
|
|
9
|
+
QUERY = """
|
|
10
|
+
{
|
|
11
|
+
"query": [
|
|
12
|
+
{
|
|
13
|
+
"code": "Region",
|
|
14
|
+
"selection": {
|
|
15
|
+
"filter": "vs:RegionKommun07EjAggr",
|
|
16
|
+
"values": [
|
|
17
|
+
"0180",
|
|
18
|
+
"1280",
|
|
19
|
+
"1480"
|
|
20
|
+
]
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
"code": "Alder",
|
|
25
|
+
"selection": {
|
|
26
|
+
"filter": "item",
|
|
27
|
+
"values": [
|
|
28
|
+
"tot20+"
|
|
29
|
+
]
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
"code": "ContentsCode",
|
|
34
|
+
"selection": {
|
|
35
|
+
"filter": "item",
|
|
36
|
+
"values": [
|
|
37
|
+
"HE0110J7"
|
|
38
|
+
]
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
"code": "Tid",
|
|
43
|
+
"selection": {
|
|
44
|
+
"filter": "item",
|
|
45
|
+
"values": [
|
|
46
|
+
"2021"
|
|
47
|
+
]
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
],
|
|
51
|
+
"response": {
|
|
52
|
+
"format": "json-stat2"
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
# From a string
|
|
58
|
+
data1 = PxWeb(URL, QUERY)
|
|
59
|
+
|
|
60
|
+
# Same query, from a file
|
|
61
|
+
data2 = PxWeb(URL, "example_query.json")
|
|
62
|
+
|
|
63
|
+
# The object can be instantiated without running the query immediately
|
|
64
|
+
# by setting the autofetch flag to `False`
|
|
65
|
+
data3 = PxWeb(URL, QUERY, autofetch=False)
|
|
66
|
+
|
|
67
|
+
# Instead we can fetch the data later on if we want to
|
|
68
|
+
data3.get_data()
|
|
69
|
+
|
|
70
|
+
# The get_data() function can be used to refresh data as well
|
|
71
|
+
|
|
72
|
+
# Everytime get_data() is called, the field "last_refresh"
|
|
73
|
+
# is updated with a timestamp (datetime).
|
|
74
|
+
data3.last_refresh
|
|
75
|
+
|
|
76
|
+
# The objects also contain the metadata of the PxWeb table
|
|
77
|
+
# such as "label", "source" and "updated".
|
|
78
|
+
data3.metadata
|
|
79
|
+
|
|
80
|
+
# The dataset itself can easily be turned into a pandas dataframe...
|
|
81
|
+
pandas_df = pd.DataFrame(data3.dataset)
|
|
82
|
+
|
|
83
|
+
# ...or a polars dataframe
|
|
84
|
+
polars_df = pl.DataFrame(data3.dataset)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
{
|
|
2
|
+
"query": [
|
|
3
|
+
{
|
|
4
|
+
"code": "Region",
|
|
5
|
+
"selection": {
|
|
6
|
+
"filter": "vs:RegionKommun07EjAggr",
|
|
7
|
+
"values": [
|
|
8
|
+
"0180",
|
|
9
|
+
"1280",
|
|
10
|
+
"1480"
|
|
11
|
+
]
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
{
|
|
15
|
+
"code": "Alder",
|
|
16
|
+
"selection": {
|
|
17
|
+
"filter": "item",
|
|
18
|
+
"values": [
|
|
19
|
+
"tot20+"
|
|
20
|
+
]
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
"code": "ContentsCode",
|
|
25
|
+
"selection": {
|
|
26
|
+
"filter": "item",
|
|
27
|
+
"values": [
|
|
28
|
+
"HE0110J7"
|
|
29
|
+
]
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
"code": "Tid",
|
|
34
|
+
"selection": {
|
|
35
|
+
"filter": "item",
|
|
36
|
+
"values": [
|
|
37
|
+
"2021"
|
|
38
|
+
]
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
],
|
|
42
|
+
"response": {
|
|
43
|
+
"format": "json-stat2"
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "pxwebpy"
|
|
3
|
+
version = "0.2.0"
|
|
4
|
+
description = "Get data from PxWeb API easily."
|
|
5
|
+
license = "MIT"
|
|
6
|
+
repository = "https://github.com/stefur/pxwebpy/"
|
|
7
|
+
keywords = ["pxweb", "statistics", "dataframes", "pandas", "polars"]
|
|
8
|
+
classifiers = [
|
|
9
|
+
"License :: OSI Approved :: MIT License",
|
|
10
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
11
|
+
"Programming Language :: Python :: 3.11",
|
|
12
|
+
"Programming Language :: Python :: 3.12",
|
|
13
|
+
]
|
|
14
|
+
authors = [
|
|
15
|
+
{ name = "stefur", email = "stefan@furne.net" }
|
|
16
|
+
]
|
|
17
|
+
dependencies = [
|
|
18
|
+
"requests>=2.31.0",
|
|
19
|
+
]
|
|
20
|
+
readme = "README.md"
|
|
21
|
+
requires-python = ">= 3.11"
|
|
22
|
+
|
|
23
|
+
[project.urls]
|
|
24
|
+
"Issue tracker" = "https://github.com/stefur/pxwebpy/issues"
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
ci = [
|
|
28
|
+
"pytest>=8.0.0",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[build-system]
|
|
32
|
+
requires = ["hatchling"]
|
|
33
|
+
build-backend = "hatchling.build"
|
|
34
|
+
|
|
35
|
+
[tool.rye]
|
|
36
|
+
managed = true
|
|
37
|
+
dev-dependencies = [
|
|
38
|
+
"pytest>=8.0.0",
|
|
39
|
+
"types-requests>=2.31.0.20240125",
|
|
40
|
+
"polars>=0.20.7",
|
|
41
|
+
"pandas>=2.2.0",
|
|
42
|
+
"pandas-stubs>=2.1.4.231227",
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
[tool.hatch.metadata]
|
|
46
|
+
allow-direct-references = true
|
|
47
|
+
|
|
48
|
+
[tool.hatch.build.targets.wheel]
|
|
49
|
+
packages = ["src/pxwebpy"]
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# generated by rye
|
|
2
|
+
# use `rye lock` or `rye sync` to update this lockfile
|
|
3
|
+
#
|
|
4
|
+
# last locked with the following flags:
|
|
5
|
+
# pre: false
|
|
6
|
+
# features: []
|
|
7
|
+
# all-features: false
|
|
8
|
+
# with-sources: false
|
|
9
|
+
|
|
10
|
+
-e file:.
|
|
11
|
+
certifi==2024.2.2
|
|
12
|
+
charset-normalizer==3.3.2
|
|
13
|
+
idna==3.6
|
|
14
|
+
iniconfig==2.0.0
|
|
15
|
+
numpy==1.26.4
|
|
16
|
+
packaging==23.2
|
|
17
|
+
pandas==2.2.0
|
|
18
|
+
pandas-stubs==2.1.4.231227
|
|
19
|
+
pluggy==1.4.0
|
|
20
|
+
polars==0.20.7
|
|
21
|
+
pytest==8.0.0
|
|
22
|
+
python-dateutil==2.8.2
|
|
23
|
+
pytz==2024.1
|
|
24
|
+
requests==2.31.0
|
|
25
|
+
six==1.16.0
|
|
26
|
+
types-pytz==2024.1.0.20240203
|
|
27
|
+
types-requests==2.31.0.20240125
|
|
28
|
+
tzdata==2023.4
|
|
29
|
+
urllib3==2.2.0
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# generated by rye
|
|
2
|
+
# use `rye lock` or `rye sync` to update this lockfile
|
|
3
|
+
#
|
|
4
|
+
# last locked with the following flags:
|
|
5
|
+
# pre: false
|
|
6
|
+
# features: []
|
|
7
|
+
# all-features: false
|
|
8
|
+
# with-sources: false
|
|
9
|
+
|
|
10
|
+
-e file:.
|
|
11
|
+
certifi==2024.2.2
|
|
12
|
+
charset-normalizer==3.3.2
|
|
13
|
+
idna==3.6
|
|
14
|
+
requests==2.31.0
|
|
15
|
+
urllib3==2.2.0
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""Namespace flattening"""
|
|
2
2
|
from pxwebpy.pxwebpy import PxWeb # noqa
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""Helper to make fetching data from PxWeb a bit easier"""
|
|
2
|
+
import itertools
|
|
3
|
+
import json
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from warnings import warn
|
|
7
|
+
|
|
8
|
+
import requests
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class PxWeb:
|
|
12
|
+
"""
|
|
13
|
+
A helper object to get data from the PxWeb API.
|
|
14
|
+
The table dataset is collected as a long format.
|
|
15
|
+
|
|
16
|
+
Parameters
|
|
17
|
+
----------
|
|
18
|
+
url : str
|
|
19
|
+
The PxWeb API URL for the table to query.
|
|
20
|
+
query : str | dict
|
|
21
|
+
The query must be a JSON structure, supplied either as a dict, string or a string representing a path to a file.
|
|
22
|
+
autofetch : bool, default True
|
|
23
|
+
Whether to automatically fetch data from the URL upon instantiation of the object.
|
|
24
|
+
|
|
25
|
+
Example
|
|
26
|
+
--------
|
|
27
|
+
Fetching data with a very simple query and turning it into a Pandas dataframe:
|
|
28
|
+
|
|
29
|
+
>>> from pxwebpy import PxWeb
|
|
30
|
+
>>> import pandas as pd
|
|
31
|
+
|
|
32
|
+
>>> URL = "https://api.scb.se/OV0104/v1/doris/sv/ssd/START/HE/HE0110/HE0110A/SamForvInk1"
|
|
33
|
+
|
|
34
|
+
>>> QUERY = {
|
|
35
|
+
"query": [
|
|
36
|
+
{
|
|
37
|
+
"code": "Tid",
|
|
38
|
+
"selection": {
|
|
39
|
+
"filter": "item",
|
|
40
|
+
"values": [
|
|
41
|
+
"2021"
|
|
42
|
+
]
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
],
|
|
46
|
+
"response": {
|
|
47
|
+
"format": "json-stat2"
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
>>> tbl = PxWeb(URL, QUERY)
|
|
52
|
+
>>> print(tbl)
|
|
53
|
+
|
|
54
|
+
PxWeb(url='https://api.scb.se/OV0104/v1/doris/sv/ssd/START/HE/HE0110/HE0110A/SamForvInk1',
|
|
55
|
+
query={'query': [{'code': 'Tid', 'selection': {'filter': 'item', 'values': ['2021']}}], 'response': {'format': 'json-stat2'}},
|
|
56
|
+
metadata={'label': 'Sammanräknad förvärvsinkomst för boende i Sverige hela året efter ålder, tabellinnehåll och år', 'source': 'SCB', 'updated': '2023-01-10T10:42:00Z'},
|
|
57
|
+
last_refresh=2023-10-29 14:21:57.628639,
|
|
58
|
+
dataset=[{'ålder': 'totalt 16+ år', 'tabellinnehåll': 'Medelinkomst, tkr', 'år': '2021' ...
|
|
59
|
+
|
|
60
|
+
>>> df = pd.DataFrame(tbl.dataset)
|
|
61
|
+
>>> print(df)
|
|
62
|
+
ålder tabellinnehåll år value
|
|
63
|
+
0 totalt 16+ år Medelinkomst, tkr 2021 331.5
|
|
64
|
+
1 totalt 16+ år Medianinkomst, tkr 2021 301.5
|
|
65
|
+
2 totalt 16+ år Totalsumma, mnkr 2021 2779588.9
|
|
66
|
+
3 totalt 16+ år Antal personer 2021 8383640.0
|
|
67
|
+
4 16-19 år Medelinkomst, tkr 2021 28.1
|
|
68
|
+
.. ... ... ... ...
|
|
69
|
+
71 80-84 år Antal personer 2021 290684.0
|
|
70
|
+
72 85+ år Medelinkomst, tkr 2021 214.4
|
|
71
|
+
73 85+ år Medianinkomst, tkr 2021 200.1
|
|
72
|
+
74 85+ år Totalsumma, mnkr 2021 57529.3
|
|
73
|
+
75 85+ år Antal personer 2021 268320.0
|
|
74
|
+
|
|
75
|
+
[76 rows x 4 columns]
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
def __init__(self, url, query, autofetch=True) -> None:
|
|
79
|
+
self.url: str = url
|
|
80
|
+
self.query: dict = query
|
|
81
|
+
self.dataset: list[dict] | None = None
|
|
82
|
+
self.metadata: dict = {
|
|
83
|
+
key: None for key in ["label", "note", "source", "updated"]
|
|
84
|
+
}
|
|
85
|
+
self.last_refresh: datetime | None = None
|
|
86
|
+
|
|
87
|
+
try:
|
|
88
|
+
response_format = self.query["response"]["format"]
|
|
89
|
+
if response_format != "json-stat2":
|
|
90
|
+
raise TypeError(
|
|
91
|
+
f"""Response format must be 'json-stat2', \
|
|
92
|
+
got '{self.query["response"]["format"]}'."""
|
|
93
|
+
)
|
|
94
|
+
except Exception as err:
|
|
95
|
+
print(f"An error occured: {err}")
|
|
96
|
+
raise Exception("Invalid query format.") from err
|
|
97
|
+
|
|
98
|
+
if autofetch:
|
|
99
|
+
self.get_data()
|
|
100
|
+
|
|
101
|
+
def __repr__(self) -> str:
|
|
102
|
+
return f"""PxWeb(url='{self.url}',
|
|
103
|
+
query={self.query},
|
|
104
|
+
metadata={self.metadata},
|
|
105
|
+
last_refresh={self.last_refresh},
|
|
106
|
+
dataset={self.dataset})"""
|
|
107
|
+
|
|
108
|
+
def get_data(self) -> None:
|
|
109
|
+
"""Get data from the API"""
|
|
110
|
+
response = requests.post(self.url, json=self.query, timeout=10)
|
|
111
|
+
if response.status_code == 200:
|
|
112
|
+
json_data = json.loads(response.text)
|
|
113
|
+
|
|
114
|
+
self.dataset = self._unpack_data(json_data)
|
|
115
|
+
|
|
116
|
+
metadata_keys = ["label", "note", "source", "updated"]
|
|
117
|
+
|
|
118
|
+
self.metadata = self.metadata = {
|
|
119
|
+
key: json_data.get(key) for key in metadata_keys
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
self.last_refresh = datetime.now()
|
|
123
|
+
|
|
124
|
+
else:
|
|
125
|
+
warn(f"Failed to retrieve data: {response.status_code}: {response.reason}")
|
|
126
|
+
|
|
127
|
+
def _unpack_data(self, response: dict) -> list[dict]:
|
|
128
|
+
"""
|
|
129
|
+
Takes the response json-stat2 and turns it into a list of dicts that can
|
|
130
|
+
be used to convert into a dataframe, using either pandas or polars.
|
|
131
|
+
"""
|
|
132
|
+
if response is None:
|
|
133
|
+
raise ValueError("response cannot be None.")
|
|
134
|
+
|
|
135
|
+
response_dims = response["dimension"]
|
|
136
|
+
|
|
137
|
+
category_labels = {}
|
|
138
|
+
for dim in response_dims:
|
|
139
|
+
label = response_dims[dim]["category"]["label"]
|
|
140
|
+
category_labels.update({response_dims[dim]["label"]: label.values()})
|
|
141
|
+
|
|
142
|
+
result = [
|
|
143
|
+
dict(zip(category_labels.keys(), x))
|
|
144
|
+
for x in itertools.product(*category_labels.values())
|
|
145
|
+
]
|
|
146
|
+
|
|
147
|
+
all_values = response["value"]
|
|
148
|
+
|
|
149
|
+
for value, dict_row in zip(all_values, result):
|
|
150
|
+
dict_row.update({"value": value})
|
|
151
|
+
|
|
152
|
+
return result
|
|
153
|
+
|
|
154
|
+
def _is_path(self, query: str) -> bool:
|
|
155
|
+
"""Check if query is a path or not"""
|
|
156
|
+
try:
|
|
157
|
+
path = Path(query)
|
|
158
|
+
return path.exists()
|
|
159
|
+
except Exception:
|
|
160
|
+
return False
|
|
161
|
+
|
|
162
|
+
@property
|
|
163
|
+
def query(self) -> dict:
|
|
164
|
+
"""
|
|
165
|
+
Getter for the query.
|
|
166
|
+
"""
|
|
167
|
+
return self.__query
|
|
168
|
+
|
|
169
|
+
@query.setter
|
|
170
|
+
def query(self, query: str | dict) -> None:
|
|
171
|
+
"""
|
|
172
|
+
Set the JSON query from a string representing a path or a JSON structure that is either a string or a dict.
|
|
173
|
+
"""
|
|
174
|
+
|
|
175
|
+
if not isinstance(query, str | dict):
|
|
176
|
+
raise TypeError(
|
|
177
|
+
f"""Invalid input for `query`.
|
|
178
|
+
Expected `str` or `dict`, got {type(query)!r}."""
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
if isinstance(query, str):
|
|
182
|
+
if self._is_path(query):
|
|
183
|
+
with open(query, mode="r", encoding="utf-8") as read_file:
|
|
184
|
+
self.__query = json.load(read_file)
|
|
185
|
+
else:
|
|
186
|
+
try:
|
|
187
|
+
self.__query = json.loads(query)
|
|
188
|
+
except Exception as err:
|
|
189
|
+
raise ValueError(
|
|
190
|
+
"Provided value could not be decoded as JSON."
|
|
191
|
+
) from err
|
|
192
|
+
else:
|
|
193
|
+
self.__query = query
|