Unable to Access API - python-3.x

I am unable to access an API.
This is what I am doing:
import os, re
import requests
import logger
from requests_oauthlib import OAuth1
oauth_consumer_key = "123abc"
oauth_secret = "aaabbbccc"
url = "https://example_testing/v1/<ID_VALUE>/reports?"
oauth = OAuth1(oauth_consumer_key, oauth_secret)
output = requests.get(url,auth=oauth)
I keep getting a 500 error.
What am I doing wrong?

I didn't know this but apparently I needed to set values for headers and the payload. This solved my problem.
headers = {"Content-Type": "application/json"}
payload = json.dumps({
"report_format":"csv",
<other stuff>
}
output = requests.get(url=url, auth=oauth, headers=headers, data=payload)
Problem Solved

Related

How do I pass an API Token into Cookie via Python Request?

I'm having issues w/ authenticating to pkgs.org api, a token was produced, by support mentioned it needs to be passed as a cookie. I've never worked with cookies before.
import requests
import json
import base64
import urllib3
import sys
import re
import os
token=('super-secret')
#s = requests.Session()
head = {'Accept':'application/json'}
r = requests.get('https://api.pkgs.org/v1/distributions', auth=(token), headers=head)
print(r)
print(r.connection)
print(r.cookies)
I tried to use the request.session method, to handle the cookie, but i honestly don't know syntax on how to ever 1 create a cookie, let alone pass the cookie.
If I read the API documentation correctly you should set acces_token cookie:
import requests
token = "super-secret"
cookies = {"access_token": token}
headers = {"Accept": "application/json"}
r = requests.get(
"https://api.pkgs.org/v1/distributions", cookies=cookies, headers=headers
)

Why is django test client throwing away my extra headers

I'm trying to test a view that makes use of some headers. In my test code I have something like this:
headers = {'X-Github-Event': 'pull_request'}
body = {useful stuff}
url = reverse(my_view)
I've tried making requests to my view using all possible combinations of the following clients and post calls:
client = Client(extra=headers)
client = APIClient(headers=headers)
client = APIClient(extra=headers)
response = client.post(url, data=body, format="json", headers=headers)
response = client.post(url, data=body, format="json", extra=headers)
My view effectively looks like this:
#api_view(["POST", "GET"])
def github_webhook(request):
print(request.headers)
My X-Github-Event header is never printed out by my view when it is called from my test code.
If I run runserver and send a request to that endpoint then the headers work perfectlty fine. It's just the test code that is broken.
What am I missing here? How can I set the headers for my tests?
I think that the following snippet will help you:
import json
from django.test import TestCase
from rest_framework.test import APIClient
class FooTestCase(TestCase):
def setUpTestData(cls):
cls.client = APIClient(ACCEPT='application/json')
def test_foo(self):
headers = {"ACCEPT": "application/json", 'HTTP_X_GITHUB_EVENT': 'pull_request'}
url = reverse(my_view)
payload = json.dumps(body)
response = self.client.post(url, data=payload, content_type='application/json', **headers)

Make multipart/form-data post requests with python

Im trying To Make post requests (multipart/form-data) in this website https://gofile.io/?t=api
every time time i got an error when i try to upload file
my code
import requests
req = requests.session()
files= {'file': open("test.txt", 'rb')}
response = req.post('https://srv-file7.gofile.io/upload', files=files)
print(response.text)
I got error every time ,are smething missing in the code
from requests_toolbelt.multipart.encoder import MultipartEncoder
import requests
import json
mp_encoder = MultipartEncoder(
fields={
'filesUploaded': ('file_name.txt', open('file_name.txt', 'rb'))
}
)
r = requests.post(
'https://srv-file9.gofile.io/upload',
data=mp_encoder,
headers={'Content-Type': mp_encoder.content_type}
)
scrap = r.json()
# send "Token file" 123Abc
Token = scrap['data']['code']
Check this. It will work.

Can't send proper post request with file using python3 requests

I was using Postman to send post request like on the screenshot
Now I need to implement it in python. This is what i've got for now:
import requests
data = {"sendRequest": {"apiKey": 12345, "field1": "field1value"}}
files = {"attachment": ("file.txt", open("file.txt", "rb"))}
headers = {"Content-type": "multipart/form-data"}
response = requests.post(endpoint, data=data, headers=headers, files=files)
But still it's not working - server doesn't accept it as valid request. I've tried more combinations but without any results and I really couldn't find a solution.
I need this request to be exactly like that one in postman
I finally found a solution. I used MultipartEncoder from requests_toolbelt library.
from requests_toolbelt import MultipartEncoder
import requests
import json
data = {"apiKey": 12345, "field1": "field1value"}}
mp = MultipartEncoder(
fields={
'sendRequest': json.dumps(data), # it is important to convert dict into json
'attachment': ('file.pdf', open('file.pdf', 'rb'), 'multipart/form-data'),
}
)
r = requests.post(ENDPOINT, data=mp, headers={'Content-Type': mp.content_type})

MissingSchema - Invalid URL Error with Requests module

Trying to get data from the eBay API using GetItem. But requests isn't reading or getting the URL properly, any ideas? Getting this error:
requests.exceptions.MissingSchema: Invalid URL '<urllib.request.Request object at 0x00E86210>': No schema supplied. Perhaps you meant http://<urllib.request.Request object at 0x00E86210>?
I swear I had this code working before but now it's not, so I'm not sure why.
My code:
from urllib import request as urllib
import requests
url = 'https://api.ebay.com/ws/api.dll'
data = '''<?xml version="1.0" encoding="utf-8"?>
<GetItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">
<RequesterCredentials>
<eBayAuthToken>my-auth-token</eBayAuthToken>
</RequesterCredentials>
<ItemID>any-item-id</ItemID>
</GetItemRequest>'''
headers = {
'Content-Type' : 'text/xml',
'X-EBAY-API-COMPATIBILITY-LEVEL' : 719,
'X-EBAY-API-DEV-NAME' : 'dev-name',
'X-EBAY-API-APP-NAME' : 'app-name',
'X-EBAY-API-CERT-NAME' : 'cert-name',
'X-EBAY-API-SITEID' : 3,
'X-EBAY-API-CALL-NAME' : 'GetItem',
}
req = urllib.Request(url, data, headers)
resp = requests.get(req)
content = resp.read()
print(content)
Thank you in advance. Any good reading material for urllib would be great, too.
You are mixing the urllib and the requests library. They are different libraries that can both do HTTP-requests in Python. I'd suggest you use only the requests library.
Remove the line req = urllib.Request(url, data, headers) and replace the resp = ... line with:
r = requests.post(url, data=data, headers=headers)
Print the response body like this:
print(r.text)
Check out the Requests Quickstart here for more examples: https://2.python-requests.org//en/master/user/quickstart/

Resources