More
referral
Increase your income with Hive. Invite your friends and earn real cryptocurrency!

Hive API v2

Простой bash скрипт с некоторыми распространенными функциями.
Возможно, кому-то пригодится в качестве примера.
+++++++++++++++++
A simple bash script with some common functions.
Perhaps someone will come in handy as an example.

Привет. Когда можно ожидать паблик АПИ для hiveon?

Здравствуйте, подскажите пожалуйста что я не так делаю, написал скрипт на python на запросы без передачи параметров приходит нужная информация нормально, но когда я передаю параметры например что бы изменить Имя фермы мне приходит ответ:
<Response [400]>
{‘message’: ‘Empty input’}
Работаю с библиотекой requests, параметры передаю в data={ “name”: “Test_farm”}
Вот сам код скрипта:

from requests import request, exceptions
from time import sleep


class Hive(object):

    def __init__(self, token):
        self.token = token

    def api_query(self, method, command, payload=None, params=None):

        if payload is None:
            payload = {}
        if params is None:
            params = {}
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + self.token
        }

        while True:
            try:
                s = request(method, 'https://api2.hiveos.farm/api/v2' + command, data=payload, params=params,
                            headers=headers, timeout=10)
            except exceptions.ConnectionError:
                print('Oops. Подключение не удалось к HiveOs')
                sleep(15)
                continue
            except exceptions.Timeout:
                print('Oops. Закончилось время ожидания ответа от HiveOs')
                sleep(15)
                continue
            except exceptions.TooManyRedirects:
                print('Oops. Превышенно количество запросов от HiveOs, Ждём 30 минут')
                sleep(1800)
                continue
            else:
                print(s)
                api = s.json()
                break

        return api

    def get_farms(self):
        return self.api_query('GET', '/farms')

    def create_farm(self):
        return self.api_query('POST', '/farms')

    def edit_farm(self, farm_id, params):
        return self.api_query('PATCH', '/farms/' + farm_id, params)


def main():

    cHive = Hive('Мой токен HiveOs')
    farm_id = 'ID нужной фермы'
    data = {
        "name": "Test farm"
    }
    print(cHive.edit_farm(farm_id, data))


if __name__ == '__main__':
    main()

Буду благодарен за любую помощь, может у кого то есть уже готовые примеры на python

1 Like

С питоном не знаком, но payload в запросе должен быть JSON, и судя по коду думаю проблема в этом…

Спасибо большое, проблема была в этом и всё получилось, сделал запрос такого вида:

print(cHive.edit_farm(farm_id, json.dumps(data)))

Подскажите, есть необходимость такого:

Создал в полётных листах несколько записей. Нужно чтобы эти записи по кругу менялись через 20 минут.

Как это сделать?

В хайве такого функционала пока нет. Но используя апи вы можете применять полетные листы самостоятельно, используя любой эндпоинт с параметром fs_id:
PATCH /farms/{farmId}/workers
PATCH /farms/{farmId}/workers/{workerId}

2 Likes

Самому менять не удобно.
Думал, что можно автоматизировать процесс.
Да и никогда не настраивал ничего через api

Было бы хорошо, если в Хайв добавили такую возможность.

Hey guys,

we are new around, therefore “Hello to everyone!”.

At the moment we are starting to have a look on the promising API, we could query with the provided examples, if we turn off our 2FA.

But is it possible to connect with enabled 2FA through an API Key only or something similar?

Background of my question is, that we’d like to have the protection through 2FA for changes / management over the Farm Website. But for our own monitoring and data logging we’d like to automate the queries and couldn’t easily use 2FA for API Calls.

Many thanks in advance!

Best regards
O.

Hi,
2FA is needed only for log in with password. When connecting with API key 2FA is not needed.
By the way whitelist IPs are checked on every connection, even when using API key.

Hi vadimz,

thank you, this is perfect, that’s exactly the way we want to use it.
I’ve already generated a personal API key within my login.

But where / how i’ve to pass that API key? I’m currently using the Bash client sample.

response=`curl -s -w "\n%{http_code}" \
         -H "Content-Type: application/json" \
         -X POST \
         -d "{\"login\":\"$login\",\"password\":\"$password\"}" \ <-- must be an option over here, i think?
         "$baseUrl/auth/login"`

I haven’t found the API parameter for the API key within the API documentation:

https://forum.hiveos.farm/discussion/192/hive-api --> Site seems down

and

https://app.swaggerhub.com/apis/HiveOS/public/2.1-beta#/auth/post_auth_login

Maybe you can help me further where to find it?

Many thanks in advance!

Best regards
O.

You don’t need to log in if you already have a token.
Just use the API with that token - pass it in special header “Authorization: Bearer $token”.

1 Like

Happy new year vadimz,

perfect, thank you - now it’s working!

Best regards
O.

Hi guys,

here you can find a Laravel package for interacting with Hive OS api

Ругается… что ему не нравится ?

1.sh: 21: 1.sh: function: not found
1.sh: 30: 1.sh: [[: not found
1.sh: 30: 1.sh: 200: not found
1.sh: 1: 1.sh: jq: not found
1.sh: 35: 1.sh: Syntax error: “}” unexpected

1 Like

Hello,

I have created a mining monitoring program that performs scoring and statistics as well as profitability calculations. My program is under windows and is currently compatible with current currencies: ETH-ETC-ZEC
I would like to interact with my program so that it can give orders to hiveOS but I did not understand the use of hive very well
I understood that we must use the end point: https://api2.hiveos.farm/api/v2

to log in, use https://api2.hiveos.farm/api/v2/auth/login

When I enter this in a browser, I receive in response:
{
“message”: “”
}

How to authenticate on the API, the process seems complex!
I saw that there were several examples of programs in Javascript, PHP and bash.
I tried these different methods: javascript: impossible to execute the program (many errors)

Would it be possible to do the same thing as the bash but for BATCH WINDOWS ???

ooops if someone could guide me, it will be nice

Thank you for your reply
cordially

Jean Pierre

1 Like

I found the solution and I just implemented my gateway to the pc target hosting HIVEOS
by simply passing through CYGWIN and using the demo script in BASH (LINUX) on the HIVEOS forum
That way, I can run bash commands from WINDOWS

Hi.
Correct me if I’m wrong.
After login, my token is valid for 2 weeks.
To acquire new token I need to provide 2FA code.
If above are true, I’m not able to automate token refresh, so I’m not able to fully automate my monitoring solution.
Is that right?

Hi, you need to create personal API token for your monitoring system. This token never expires until you delete it.

I’m trying to use the API to switch flight sheets, but I am having the following problem:

$ curl -s -w '\n%{http_code}' -H 'Content-Type: application/json' -H 'Authorization: Bearer KEY_DELETED' -X PATCH -d '{"fs_id": X16R}' https://api2.hiveos.farm/api/v2/farms/FARM_ID_DELETED/workers/WORKER_ID_DELETED
{
    "message": "Empty input"
}

I know the API key is OK, because this works:

curl -s -w '\n%{http_code}' -H 'Content-Type: application/json' -H 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9hcGkyLmhpdmVvcy5mYXJtIiwiaWF0IjoxNTU1MzgyMTA3LCJleHAiOjE4NzIyMTA5MDcsIm5iZiI6MTU1NTM4MjEwNywianRpIjo0OTA3MTg5LCJzdWIiOjQ5MDcxODksInJtYiI6dHJ1ZX0.0BqoOA_IaQlOvEmIAjLhgtDmZJcfq16Bg0szV1Ko76E' https://api2.hiveos.farm/api/v2/farms/37906/fs
{"data":[{"id":<REST OF RESPONSE DELETED>

Any help on what I am doing wrong in trying to change the flight sheet?

Thank you!