krubsburger
krubsburger

Reputation: 91

Getting HTTPError on API request

I recently started learning Python 3 and am trying to write my first program. The essence of the program is the auto-display of items on the trading floor. I use the API https://market.csgo.com/docs-v2. Everything would be fine, if not the errors that appear while the script is running. I know to use "TRY and EXECPT", but how to do it right? My code:

while True: 
    try:
        ip = {'18992549780':'10000', '18992548863':'20000','18992547710':'30000','18992546824':'40000', '18992545927':'50000', '18992544515':'60000', '18992543504':'70000', '18992542365':'80000', '18992541028':'90000', '18992540218':'100000'}
        for key,value in ip.items():
            url3 = ('https://market.csgo.com/api/v2/add-to-sale?key=MYAPIKEY&id={id}&price={price}&cur=RUB')
            addtosale = url3.format(id = key, price = value)
            onsale = requests.get(addtosale)
            onsale.raise_for_status()
            r = onsale.json()
            print(addtosale)
            print(onsale.raise_for_status)
            print(r)
            time.sleep(5)
    except requests.HTTPError as exception:
        print(exception)

My task is to run this piece of code between TRY and EXCEPT again on any error (5xx for example)

Traceback (most recent call last):
  File "D:\Python\tmsolve1.py", line 30, in <module>
    onsale.raise_for_status()
  File "C:\Users\���������\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\models.py", line 941, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 502 Server Error: Bad Gateway for url: https://market.csgo.com/api/v2/add-to-sale?key=MYAPIKEY&id=18992545927&price=50000&cur=RUB
502 Server Error: Bad Gateway for url: https://market.csgo.com/api/v2/add-to-sale?key=MYAPIKEY&id=18992549780&price=10000&cur=RUB

Upvotes: 2

Views: 2176

Answers (1)

Greg
Greg

Reputation: 4518

Error handling can be done in multiple ways. You have 10 API calls. You can either stop the code on first error, retry the request or continue with additional call.

The example below will continue running through all requests.

Also except requests.HTTPError as exception may not be needed. This error is thrown by response.raise_for_status(). You can preform logging before calling .raise_for_status(). The try/catch only allows the code to continue in the loop.

import requests
import time
import json
# while True: # This will make the code loop continuously
try:
    ip = {'18992549780':'10000', '18992548863':'20000','18992547710':'30000','18992546824':'40000', '18992545927':'50000', '18992544515':'60000', '18992543504':'70000', '18992542365':'80000', '18992541028':'90000', '18992540218':'100000'}
    for key,value in ip.items():        
        url= 'https://market.csgo.com/api/v2/add-to-sale'
        payload = {'key': 'MYAPIKEY', 'id': id, 'price': value, 'cur': 'RUB'}        
        response = requests.get(url, params=payload)
        print(f'Status code: { response.status_code}')
        print(f'Response text: { response.text}') # This will contain an error message or json results.
        response.raise_for_status() # This will only error if status code is 4xx or 5xx        
        results = response.json()

        if results.get('error'): #  "results" can contains {"error":"Bad KEY","success":false}
            raise Exception('Error in response json')

        print(json.dumps(results))
        time.sleep(5)
except requests.HTTPError as exception: # Captures response.raise_for_status() - 4xx or 5xx status code. If you remove this, then code will use generic handle        
    print(exception)
except Exception as exception: # Generic error handler for raise Exception('Error in response json') and "Max retries exceeded."
    print(exception)

Upvotes: 1

Related Questions