'Python : Bypass Error message from API server
I'm using a Python script to get Stock price from an API, Everythinks works great but sometimes I receive html errors instead of prices, These errors prevent the script from continuing and the terminal stopped working, how do I test the response from the API before passing the information to the next script? I don't want the terminal to stop when it receives server errors. Only one line to get price :
get_price = api_client.quote('TWTR')
Solution 1:[1]
The question, "How do I test the response from the API before passing the information" is well suited for a try/except block. For example the following will attempt to call quote() and if an exception is raised it will print a message to the console:
try:
get_price = api_client.quote('TWTR')
except <Exception Type Goes Here>:
# handle the exception case.
print('Getting quote did not work as expected')
The example is useful for illustrating the point but you should improve the exception handling. I recommend you take a look at resources to help you understand how to appropriately handle exceptions in your code. A few that I have found useful would be:
- The Python Docs: Learn what an exception is and how they can be used
- Python Exception Handling: A blog post that details how to combine some of the concepts in the Python documentation practically.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nathan |
