how to make a release using the github api - python

I tried to do it by examples, but at startup it outputs a 404 error
import requests
payload ={"tag_name":"v1.0.0","target_commitish":"master","name":"v1.0.0","body":"Description of the release","draft":"false","prerelease":"false","generate_release_notes":"false"}
url = 'https://api.github.com/repos/user/test/releases'
headers = {'Authorization': 'token token'}
response = requests.post(url, headers=headers,data=payload)
print(response)

Try:
import requests
payload ={"tag_name":"v1.0.0","target_commitish":"master","name":"v1.0.0","body":"Description of the release","draft":"false","prerelease":"false","generate_release_notes":"false"}
url = 'https://api.github.com/repos/user/test/releases'
headers = {'Authorization': 'token token', 'Accept': 'application/vnd.github+json'}
response = requests.post(url, headers=headers, json=payload)
print(response)

Related

How to create a simple REST api WEB application with Python

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'])

When I use the spotify api to search for a song, and print the response, it is always showing response code[502]

Here is the code for it
from urllib import parse
import os
import requests
api_token = os.getenv('SPOTIFY_AUTH_TOKEN')
query = parse.quote('Hardwell Power')
url = f'https://api.spotify.com/v1/search?q={query}&type=track'
response = requests.get(
url,
headers={
'Accept': 'application/json',
'Content Type': 'application/json',
'Authorization': f'Bearer {api_token}'
}
)
print(response)
Here is the output
<Response [502]>
Can anyone please point out the mistake and help me?
To get the other stuff from response try using print(response.json()) or print(response.text)

electrum JsonRPC Invalid request

I'm trying to use electrum wallet
I have this code :
import json
import requests
if __name__ == "__main__":
headers = {'content-type': "application/json", 'cache-control': "no-cache"}
payload = json.dumps({"method": 'listaddresses', "params": []})
url = f"http://127.0.0.1:7777"
print(payload)
response = requests.request("POST", url, data=payload, headers=headers,
auth=('user', 'mypass'))
print(response)
print(response.text)
print(response.json)
But i got this error :
<Response [500]>
Invalid Request
I should get an error, but not a 500 error.
It's not lot of info :/ Do you have any idea of what i'm doing wrong ?
after night i found the error.
The payload should be like this :
payload = json.dumps({"jsonrpc":"2.0","id":"curltext", "method": method, "params": params})
with jsonrpc & id

Issues Accessing SOAP service with Python

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)

how to use Google Shortener API with Python

I want to write an app to shorten url. This is my code:
import urllib, urllib2
import json
def goo_shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url'
postdata = urllib.urlencode({'longUrl':url})
headers = {'Content-Type':'application/json'}
req = urllib2.Request(
post_url,
postdata,
headers
)
ret = urllib2.urlopen(req).read()
return json.loads(ret)['id']
when I run the code to get a tiny url, it throws an exception: urllib2.HTTPError: HTTP Error 400: Bad Requests.
What is wrong with this code?
I tried your code and couldn't make it work either, so I wrote it with requests:
import requests
import json
def goo_shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url'
payload = {'longUrl': url}
headers = {'content-type': 'application/json'}
r = requests.post(post_url, data=json.dumps(payload), headers=headers)
print(r.text)
Edit: code working with urllib:
def goo_shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url'
postdata = {'longUrl':url}
headers = {'Content-Type':'application/json'}
req = urllib2.Request(
post_url,
json.dumps(postdata),
headers
)
ret = urllib2.urlopen(req).read()
print(ret)
return json.loads(ret)['id']
I know this question is old but it is high on Google.
Another thing to try is the pyshorteners library it is very simple to implement.
Here is a link:
https://pypi.python.org/pypi/pyshorteners
With an api key:
import requests
import json
def shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(API_KEY)
payload = {'longUrl': url}
headers = {'content-type': 'application/json'}
r = requests.post(post_url, data=json.dumps(payload), headers=headers)
return r.json()

Categories

Resources