Reinaldo Chaves
Reinaldo Chaves

Reputation: 995

How to filter values in API with Python?

In Python 3 I made this program to read an API of government contracts in Brazil (http://compras.dados.gov.br)

My intention was to access the contracts module (http://compras.dados.gov.br/docs/contratos/v1/contratos.html)

Example: http://compras.dados.gov.br/contratos/v1/contratos.html?uasg=153229

Example in JSON: http://compras.dados.gov.br/contratos/v1/contratos.json?uasg=153229

I made a program for the "cnpj_contratada" field:

import requests
import pandas as pd

url = 'http://compras.dados.gov.br'
cnpj = '92781335000102' #code example

url = '{0}/contratos/v1/contratos.json?cnpj_contratada={1}'.format(url, cnpj)

r = requests.get(url)
contracts = r.json()['_embedded']['contratos']

df = pd.DataFrame(contracts)
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 41 entries, 0 to 40
Data columns (total 18 columns):
_links                    41 non-null object
cnpj_contratada           41 non-null object
codigo_contrato           41 non-null int64
data_assinatura           41 non-null object
data_inicio_vigencia      41 non-null object
data_termino_vigencia     41 non-null object
fundamento_legal          41 non-null object
identificador             41 non-null object
licitacao_associada       41 non-null object
modalidade_licitacao      41 non-null int64
numero                    41 non-null int64
numero_aditivo            5 non-null float64
numero_aviso_licitacao    41 non-null int64
numero_processo           41 non-null object
objeto                    41 non-null object
origem_licitacao          41 non-null object
uasg                      41 non-null int64
valor_inicial             41 non-null float64
dtypes: float64(2), int64(5), object(11)
memory usage: 5.8+ KB

My intention is now to use the "valor_inicial" field. I just want to access contract values equal or greater than 100000000.0

url = 'http://compras.dados.gov.br'
valor = 100000000.0
url = '{0}/contratos/v1/contratos.json?valor_inicial>={1}'.format(url, valor)
r = requests.get(url)
print(r)
<Response [500]>

If I put ">=" the location of the url logically goes wrong. Please, would anyone know how to filter the values?

Upvotes: 0

Views: 80

Answers (2)

proparokani
proparokani

Reputation: 1

How about passing valor_inicial_min parameter to URLs?

http://compras.dados.gov.br/contratos/v1/contratos.json?valor_inicial_min=100000000.0

Upvotes: 0

Szabolcs
Szabolcs

Reputation: 4086

According to the API documentation http://compras.dados.gov.br/docs/contratos/v1/contratos.html, you can use the valor_inicial_min for this purpose.

So can you try this please:

url = 'http://compras.dados.gov.br'
valor = 100000000.0
url = '{0}/contratos/v1/contratos.json?valor_inicial_min={1}'.format(url, valor)
r = requests.get(url)
print(r)

Hope it helps.

Upvotes: 2

Related Questions