Skip to content

Commit 14ee173

Browse files
committed
Add get_json function and corresponding tests for JSON response handling
Issues #22 and #21
1 parent 78d1afd commit 14ee173

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

bcb/sgs/__init__.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,3 +137,44 @@ def get(codes, start=None, end=None, last=0, multi=True, freq=None):
137137
return pd.concat(dfs, axis=1)
138138
else:
139139
return dfs
140+
141+
142+
def get_json(code: int, start=None, end=None, last: int = 0) -> str:
143+
"""
144+
Retorna um JSON com séries temporais obtidas do SGS.
145+
146+
Parameters
147+
----------
148+
149+
code : int
150+
Código da série temporal
151+
start : str, int, date, datetime, Timestamp
152+
Data de início da série.
153+
Interpreta diferentes tipos e formatos de datas.
154+
end : string, int, date, datetime, Timestamp
155+
Data final da série.
156+
Interpreta diferentes tipos e formatos de datas.
157+
last : int
158+
Retorna os últimos ``last`` elementos disponíveis da série temporal
159+
solicitada. Se ``last`` for maior que 0 (zero) os argumentos ``start``
160+
e ``end`` são ignorados.
161+
162+
Returns
163+
-------
164+
165+
JSON :
166+
série temporal univariada em formato JSON.
167+
"""
168+
urd = _get_url_and_payload(code, start, end, last)
169+
res = requests.get(urd["url"], params=urd["payload"])
170+
if res.status_code != 200:
171+
try:
172+
res_json = json.loads(res.text)
173+
except Exception:
174+
res_json = {}
175+
if "error" in res_json:
176+
raise Exception("BCB error: {}".format(res_json["error"]))
177+
elif "erro" in res_json:
178+
raise Exception("BCB error: {}".format(res_json["erro"]["detail"]))
179+
raise Exception("Download error: code = {}".format(code))
180+
return res.text

tests/sgs/test_series.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,3 +102,35 @@ def test_get_long_series_error():
102102
)
103103
else:
104104
assert False, "Expected an exception but none was raised."
105+
106+
107+
def test_json_return():
108+
# Test for JSON return
109+
x = sgs.get_json(1, last=10)
110+
assert isinstance(x, str)
111+
assert len(x) > 0
112+
assert x.startswith("[")
113+
assert x.endswith("]")
114+
115+
116+
def test_json_return_long_series_error():
117+
# Test for JSON return long series error
118+
try:
119+
sgs.get_json(1, start="2000-01-01", end="2023-01-01")
120+
except Exception as e:
121+
assert (
122+
str(e)
123+
== "BCB error: O sistema aceita uma janela de consulta de, no máximo, 10 anos em séries de periodicidade diária"
124+
)
125+
else:
126+
assert False, "Expected an exception but none was raised."
127+
128+
try:
129+
sgs.get_json(1, last=50)
130+
except Exception as e:
131+
assert (
132+
str(e)
133+
== "BCB error: br.gov.bcb.pec.sgs.comum.excecoes.SGSNegocioException: A quantidade máxima de valores deve ser 20"
134+
)
135+
else:
136+
assert False, "Expected an exception but none was raised."

0 commit comments

Comments
 (0)