API Request - Store JSON - Analyze it later - python

I wanting to GET a JSON request from an API and then save those values for comparison and use for another API request. First I am having trouble saving the table.
def get_sma(ticker_symbol, API):
url = f"https://api.twelvedata.com/sma?symbol={ticker_symbol}&interval=1day&time_period=200&outputsize=1&apikey={api_key}"
response = requests.get(url).json()
return response
Using this method how do I recall the response, is it using "get_sma" ?

I don't have a key, but here is how to clean up the code you posted.
import requests
def get_sma(ticker_symbol, api_key):
url = f"https://api.twelvedata.com/sma?symbol={ticker_symbol}&interval=1day&time_period=200&outputsize=1&apikey={api_key}"
response = requests.get(url).json()
return response
aapl_response = get_sma("AAPL",None)
print(aapl_response)
amzn_response = get_sma("AMZN",None)
print(amzn_response)

Related

Updating requests Response content in Python

I'm new to Python. I'm trying to make a change in the Json body that I get in an exchange response using the requests library.
I want to do something like:
import json
import requests
def request_and_fill_form_in_response() -> requests.Response():
response = requests.get('https://someurl.com')
body_json = response.json()
body_json['some_field'] = 'some_value'
response.content = json.dumps(body_json)
return response
In this particular scenario I'm only interested of updating the response.content object (regardless of if it is a good practice or not).
Is this possible?
(btw, the code above throws 'AttributeError: can't set attribute' error, which is pretty much self-explanatory, but I want to make sure I'm not missing something)
You can rewrite the content in this way:
from json import dumps
from requests import get, Response
def request_and_fill_form_in_response() -> Response:
response = get('https://mocki.io/v1/a9fbda70-f7f3-40bd-971d-c0b066ddae28')
body_json = response.json()
body_json['some_field'] = 'some_value'
response._content = dumps(body_json).encode()
return response
response = request_and_fill_form_in_response()
print(response.json())
and the result is:
{'name': 'Aryan', 'some_field': 'some_value'}
but technically _content is a private variable and there must be a method as a setter to assign a value to it.
Also, you can create your own Response object too. (you can check the response methods here)

What is the best method to return smmry api request with block of text in json instead of url?

I am trying to write a function in python that returns the json from a request to the smmry API. I was able to get it working with the SM_URL request like this:
def summry():
API_ENDPOINT = "https://api.smmry.com"
API_KEY = "B..."
params = {
"SM_API_KEY":API_KEY,
"SM_URL":"https:..."
}
r = requests.get(url=API_ENDPOINT, params=params)
return r.json()
However, I am not sure how you would do this for passing in a block of text instead of a URL. I have tried making the request with sm_api_input=my_input but that returned an error of insufficient variables. I have also tried it with a POST request and got the same error.
If anyone is curious, this is how I solved the problem. Turns out I needed an Expect: 100-continue header and the sm_api_input is a separate post field instead of a get query.
def summry(text):
API_KEY = "B..."
API_ENDPOINT = "https://api.smmry.com"
data = {
"sm_api_input":text
}
params = {
"SM_API_KEY":API_KEY
}
header_params = {"Expect":"100-continue"}
r = requests.post(url=API_ENDPOINT, params=params, data=data, headers=header_params)
return r.json()

Wit AI message API

Can someone please let me know how to make requests to Wit.ai message api. I am struggling with my code.
import requests
import json
import sys
from wit import Wit
# Wit speech API endpoint
API_ENDPOINT = 'https://api.wit.ai/message'
q='who are you'
# Wit.ai api access token
wit_access_token = 'B3GHXHLTXIASO7S4KY7UC65LMSTCDEHK'
# defining headers for HTTP request
headers = {'authorization': 'Bearer ' + wit_access_token}
# making an HTTP post request
resp = requests.post(API_ENDPOINT, headers = headers,data = {'q':'who are you'})
# converting response content to JSON format
data = json.loads(resp.content)
print(data)
I am getting back this:
{u'code': u'json-parse', u'error': u'Invalid JSON'}
The /message endpoint of Wit API accepts only GET method and expects the query parameters in URL (not data in request body). The requests library will correct the case on your lowercase Authorization header field, but it's a good practice to write it according to the standard. Also, JSON response can be fetched decoded with json() method on Response.
With all of this:
import requests
API_ENDPOINT = 'https://api.wit.ai/message'
WIT_ACCESS_TOKEN = 'B3GHXHLTXIASO7S4KY7UC65LMSTCDEHK'
headers = {'Authorization': 'Bearer {}'.format(WIT_ACCESS_TOKEN)}
query = {'q': 'who are you'}
resp = requests.get(API_ENDPOINT, headers=headers, params=query)
data = resp.json()
print(data)
Note however, Wit has a Python library which abstracts all of these low-level details, and makes your code much simpler and easier to read. Use it.
It would look like this (example from the docs):
from wit import Wit
client = Wit(access_token=WIT_ACCESS_TOKEN)
resp = client.message('what is the weather in London?')
print('Yay, got Wit.ai response: ' + str(resp))

Post array as parameters for API call

I am trying to send a tweet to the Buffer API using the POST /updates/create method. I get a 405 error as a response. I think the problem comes from the profile_ids parameter which should be an array. What is the correct syntax for this case ?
import requests
import json
url = "https://api.bufferapp.com/1/updates/create.json"
params = dict()
params['access_token'] = myToken
params["profile_ids"] = myID
params['text']= "This is a test"
r = requests.post(url, params=params)
print(r.status_code)
Please note that myToken and myID are variables I did not share for the post.

How do I parse a JSON response from Python Requests?

I am trying to parse a response.text that I get when I make a request using the Python Requests library. For example:
def check_user(self):
method = 'POST'
url = 'http://localhost:5000/login'
ck = cookielib.CookieJar()
self.response = requests.request(method,url,data='username=test1&passwd=pass1', cookies=ck)
print self.response.text
When I execute this method, the output is:
{"request":"POST /login","result":"success"}
I would like to check whether "result" equals "success", ignoring whatever comes before.
The manual suggests: if self.response.status_code == requests.codes.ok:
If that doesn't work:
if json.loads(self.response.text)['result'] == 'success':
whatever()
Since the output, response, appears to be a dictionary, you should be able to do
result = self.response.json().get('result')
print(result)
and have it print
'success'
If the response is in json you could do something like (python3):
import json
import requests as reqs
# Make the HTTP request.
response = reqs.get('http://demo.ckan.org/api/3/action/group_list')
# Use the json module to load CKAN's response into a dictionary.
response_dict = json.loads(response.text)
for i in response_dict:
print("key: ", i, "val: ", response_dict[i])
To see everything in the response you can use .__dict__:
print(response.__dict__)
import json
def check_user(self):
method = 'POST'
url = 'http://localhost:5000/login'
ck = cookielib.CookieJar()
response = requests.request(method,url,data='username=test1&passwd=pass1', cookies=ck)
#this line converts the response to a python dict which can then be parsed easily
response_native = json.loads(response.text)
return self.response_native.get('result') == 'success'
I found another solution. It is not necessary to use json module. You can create a dict using dict = eval(whatever) and return, in example, dict["result"]. I think it is more elegant. However, the other solutions also work and are correct
Put in the return of your method like this:
return self.response.json()
If you wanna looking for more details, click this following link:
https://www.w3schools.com/python/ref_requests_response.asp
and search for json() method.
Here is an code example:
import requests
url = 'https://www.w3schools.com/python/demopage.js'
x = requests.get(url)
print(x.json())
In some cases, maybe the response would be as expected. So It'd be great if we can built a mechanism to catch and log the exception.
import requests
import sys
url = "https://stackoverflow.com/questions/26106702/how-do-i-parse-a-json-response-from-python-requests"
response = requests.get(url)
try:
json_data = response.json()
except ValueError as exc:
print(f"Exception: {exc}")
# to find out why you have got this exception, you can see the response content and header
print(str(response.content))
print(str(response.headers))
print(sys.exc_info())
else:
if json_data.get('result') == "success":
# do whatever you want
pass

Categories