I am trying to access the github API via requests with python (Answers in similar questions here and here do not help).
Using curl, I am able to get a list of recent commits for a project, e.g.
curl -H "Accept: application/vnd.github.inertia-preview+json Authorization: token a0d42faabef23ab5b5462394373fc133ca107890" https://api.github.com/repos/rsapkf/42/commit
Trying to use the same setup in python with requests I tried to use
url = "https://api.github.com/repos/rsapkf/42/commits"
headers = {"Accept": "application/vnd.github.inertia-preview+json", "Authorization": "token a0d42faabef23ab5b5462394373fc133ca107890"}
r = requests.get(url, headers=headers)
as well as
url = "https://api.github.com/repos/rsapkf/42/commits"
headers = {"Accept": "application/vnd.github.inertia-preview+json"}
my_username = "someuser"
my_token = "a0d42faabef23ab5b5462394373fc133ca107890"
r = requests.get(url, headers=headers, auth=(my_username, my_token))
but in both cases I get the response
{'documentation_url': 'https://docs.github.com/rest',
'message': 'Bad credentials'}
What am I missing here?
No Authentication is required. The following works:
url = "https://api.github.com/repos/rsapkf/42/commits"
headers = {"Accept": "application/vnd.github.inertia-preview+json"}
r = requests.get(url, headers=headers)
Related
I've have been accessing an supportpal API via curl just fine using the following command. (https://docs.supportpal.com/current/REST+API)
curl.exe -i -u 'APIKEY:x' -X GET https://support.url.org/api/user/user/3697
This correctly grabs the data. I've trying replicate this with python but i continually have issues with authentication and get the following error.
Failed to authenticate because of bad credentials or an invalid authorization header
The code i'm using is straight forward.
import requests
import json
url = "https://support.url.org/api/user/user/3697"
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer: {APIKEY:x}"
}
response = requests.request("GET", url, headers=headers)
print(response. Text)
I'm thinking i have an issue with the auth header, but can't figure it out.
from requests.auth import HTTPBasicAuth
import requests
url = 'https://support.url.org/api/user/user/3697'
headers = {'Accept': 'application/json'}
auth = HTTPBasicAuth('apikey', x)
req = requests.get(url, headers=headers, auth=auth)
We can make REST api application with spring boot by start.spring.io web site easily, anyone know any good website through which I can get the skeleton REST api project with python? My intention is to make REST api application with python.
One of the ways to do this is by using the requests module in Python. Import it into your code with the following command:
import requests
Now, each API is different, so you'll have to see with the vendor what the requirements are. For testing and learning purposes, I recommend using httpbin (https://httpbin.org). You can test pretty much anything there.
Here are a few simple requests:
#returning status
url = 'https://httpbin.org/post'
response = requests.post(url)
print(response.status_code)
print(response.ok)
#sending data/getting text response
url = 'https://httpbin.org/post'
params = {'Jello':'World'}
response = requests.post(url, params=params)
print(response.text)
#sending data/getting json response
url = 'https://httpbin.org/post'
params = {'Jello':'World'}
response = requests.post(url, params=params)
print(response.json())
#sending time data to server
import datetime
url = 'https://httpbin.org/post'
params = {'Time':f'{datetime.datetime.now()}'}
response = requests.post(url, params=params)
print(response.text)
#Params vs Data
#params
url = 'https://httpbin.org/post'
params = {'username':'jsmith','password':'abc123'}
response = requests.post(url, params=params)
print(response.text)
#data
url = 'https://httpbin.org/post'
payload = {'username':'jsmith','password':'abc123'}
response = requests.post(url, data=payload)
print(response.text)
# ********* HEADERS **********
url = 'https://httpbin.org/get'
response = requests.get(url)
print(response.text)
url = 'https://httpbin.org/post'
headers = {'content-type': 'multipart/form-data'}
response = requests.post(url,headers=headers)
print(response.request.headers) #client request headers
print(response.headers) #server response headers
print(response.headers['content-type']) #request header value from server
To use actual APIs, I suggest RapidAPI (https://rapidapi.com/), which is a hub where you can connect to thousands of APIs. HEre is a sample code using Google translate:
#RapidAPI
#Google Translate
import requests
url = "https://google-translate1.p.rapidapi.com/language/translate/v2"
text = 'Ciao mondo!'
to_lang = 'en'
from_lang = 'it'
payload = f"q={text}&target={to_lang}&source={from_lang}"
headers = {
'content-type': "application/x-www-form-urlencoded",
'accept-encoding': "application/gzip",
'x-rapidapi-host': "google-translate1.p.rapidapi.com",
'x-rapidapi-key': "your-API-key"
}
response = requests.post(url, data=payload, headers=headers)
print(response.json()['data']['translations'][0]['translatedText'])
I've used postman for getting the access token from server and it's working fine. but when i copy the python code from postman and run that code in IDE it's showing some errors like max entries exceeded.
import requests
url = "https://web.com/oauth/token"
payload = "type=authorizatio&code=mycode&id=abcdefghi&client=kjsisjnsui675eaa9WqksiisP"
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)
I am attempting to access the NJTransit API, I have successfully queried it using the Postman application but no matter what I try I cannot get python to successfully return the desired query.
Using suds:
from suds.client import Client
url = "http://traindata.njtransit.com:8090/NJTTrainData.asmx?wsdl"
client = Client(url, cache = None)
from suds.sax.element import Element
auth = Element('UserCredentials')
auth.append(Element('userName').setText(my_username))
auth.append(Element('password').setText(my_password))
client.set_options(soapheaders = auth)
client = Client(url, cache = None)
result = client.service.getTrainScheduleJSON("NY")
This results in "none".
I've also attempted to use the preformatted request suggested by the Postman app, however I keep getting a 404 error.
import requests
url = "http://traindata.njtransit.com:8090/NJTTrainData.asmx"
querystring = {"wsdl":""}
payload = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Header>\n <UserCredentials xmlns=\"http://microsoft.com/webservices/\">\n <userName>---</userName>\n <password>---</password>\n </UserCredentials>\n </soap:Header>\n <soap:Body>\n <getTrainScheduleJSON xmlns=\"http://microsoft.com/webservices/\">\n <station>NY</station>\n </getTrainScheduleJSON>\n </soap:Body>\n</soap:Envelope>"
headers = {
'content-type': "text/xml; charset=utf-8",
'host': "traindata.njtransit.com",
'soapaction': "http//microsoft.com/webservices/getTrainScheduleJSON"
}
response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
print(response.text)
I would greatly appreciate any help/insight.
You never want to set the "Host" header, this is will be done by requests.
The 404 is triggered by the wrong SOAPAction. There is a missing : after http.
The following snippet is working fine for me.
import requests
url = "http://traindata.njtransit.com:8090/NJTTrainData.asmx"
querystring = {"wsdl":""}
payload = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Header>\n <UserCredentials xmlns=\"http://microsoft.com/webservices/\">\n <userName>---</userName>\n <password>---</password>\n </UserCredentials>\n </soap:Header>\n <soap:Body>\n <getTrainScheduleJSON xmlns=\"http://microsoft.com/webservices/\">\n <station>NY</station>\n </getTrainScheduleJSON>\n </soap:Body>\n</soap:Envelope>"
headers = {
'content-type': "text/xml; charset=utf-8",
'soapaction': 'http://microsoft.com/webservices/getTrainScheduleJSON'
}
response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
print response
print(response.text)
I'm trying to use requests in python to post a json dictionary to a url. I need to get a string back from the url but I keep getting a code 141 error -{"code":141,"error":"Missing a github repository link"}. I'm using this website(http://docs.python-requests.org/en/latest/user/quickstart/) to do requests.
Any ideas on why I keep getting that error? Code is below.
import requests
import json
payload = { "email" : "jade#gmail.com", "github" : "https://github.com/"}
headers = {'content-type': 'application/json', "Accept": 'application/json'}
r = requests.post("http://challenge.code2040.org/api/register", params = payload, headers = headers)
print(r.url)
print r.text
Update: The suggestion worked but now I'm getting an{"code":141,"error":"success/error was not called"} error when I try to save the response I recieve from the url into a variable and then post it back to a different url.
#Store the token into a variable
token = r.text
payload = { "token" : token}
headers = {'content-type': 'application/json', "Accept": 'application/json'}
r = requests.post("http://challenge.code2040.org/api/getstring", json = payload, headers = headers)
print r.text
Since you are making a POST request and you need to provide a JSON in the request body, use json argument, not params:
r = requests.post("http://challenge.code2040.org/api/register",
json=payload,
headers=headers)
(tested - got back a token)
Note that json argument was introduced in requests 2.4.2.