3
respostas

Erro 400

edu@edu-VirtualBox:~/Documentos/alura/datapipeline$ python3 recent_search.py 400 Traceback (most recent call last): File "/home/edu/Documentos/alura/datapipeline/recent_search.py", line 51, in main() File "/home/edu/Documentos/alura/datapipeline/recent_search.py", line 46, in main json_response = connect_to_endpoint(url, headers) File "/home/edu/Documentos/alura/datapipeline/recent_search.py", line 38, in connect_to_endpoint raise Exception(response.status_code, response.text) Exception: (400, '{"errors":[{"parameters":{"tweet.fields":["author_id,conversation_id,created_id,id,in_reply_to_user_id,public_metrics,text"]},"message":"The tweet.fields query parameter value [created_id] is not one of [attachments,author_id,context_annotations,conversation_id,created_at,entities,geo,id,in_reply_to_user_id,lang,non_public_metrics,organic_metrics,possibly_sensitive,promoted_metrics,public_metrics,referenced_tweets,reply_settings,source,text,withheld]"}],"title":"Invalid Request","detail":"One or more parameters to your request was invalid.","type":"https://api.twitter.com/2/problems/invalid-request"}')

import requests
import os
import json

    # To set your enviornment variables in your terminal run the following line:
    # export 'BEARER_TOKEN'='<your_bearer_token>'


def auth():
    return os.environ.get("BEARER_TOKEN")


def create_url():
    query = "AluraOnline"
    # Tweet fields are adjustable.
    # Options include:
    # attachments, author_id, context_annotations,
    # conversation_id, created_at, entities, geo, id,
    # in_reply_to_user_id, lang, non_public_metrics, organic_metrics,
    # possibly_sensitive, promoted_metrics, public_metrics, referenced_tweets,
    # source, text, and withheld
    tweet_fields = "tweet.fields=author_id,conversation_id,created_id,id,in_reply_to_user_id,public_metrics,text"
    user_fields = "expansions=author_id&user.fields=name,username,created_at"
    filters ="start_time=2022-05-08T00:00:00.000Z&end_time=2022-05-09T00:00:00.000Z"
    url = f"https://api.twitter.com/2/tweets/search/recent?query={query}&{tweet_fields}&{user_fields}&{filters}"
    return url


def create_headers(bearer_token):
    headers = {"Authorization": "Bearer {}".format(bearer_token)}
    return headers


def connect_to_endpoint(url, headers):
    response = requests.request("GET", url, headers=headers)
    print(response.status_code)
    if response.status_code != 200:
        raise Exception(response.status_code, response.text)
    return response.json()


def main():
    bearer_token = auth()
    url = create_url()
    headers = create_headers(bearer_token)
    json_response = connect_to_endpoint(url, headers)
    print(json.dumps(json_response, indent=4, sort_keys=True))


if __name__ == "__main__":
    main()
3 respostas

Fala Luiz, beleza? Tive o mesmo problema que você ontem e consegui resolver hoje. Inicialmente um erro que você está cometendo é:

filters ="start_time=2022-05-08T00:00:00.000Z&end_time=2022-05-09T00:00:00.000Z"

O correto seria:

filters ="start_time=2022-05-08T00:00:00:00Z&end_time=2022-05-09T00:00:00:00Z"

Agora se o erro persistir, eu diria para você fazer o que fiz que é seguir cada etapa segundo o preparando o ambiente, sem pular nada. Ativa primeiro o ambiente virtual, depois chama a variável de ambiente do airflow, ai chama a variável de ambiente do Bearer token e depois roda o código. Faça tudo isso dentro da pasta datapipeline e de preferência pelo terminal. Espero que resolva o problema.

Fala Iago, muito obrigado pela ajuda mas o erro ainda persiste, vou seguir tua dica e refazer os passos do "preparando o ambiente" , abraço irmão.

Tenta gerar um novo bearer token. O meu eu gerei 2 novos, ai desisti e voltei refazendo os passos corretos e usando um novo bearer token e rodou .