How can you build a custom endpoint on another website? - api

I am trying to get used to flask but I want to basically create a custom endpoint.
For example:
given a website is called: abc.com
I basically want to create an endpoint: abc.com/me
which would then print something like "HI"

if I understand you correctyly, this peace of code is what you want to do.
When you run the code servers up and run on the localhost:5000 in default port, if you route localhost:5000/me page shows hi. also read documantation
from flask import Flask
app = Flask(__name__)
#app.route('/me')
def me():
return 'Hi'
if __name__ == '__main__':
app.run()

Related

Request to Steam API working with curl, does not work in browser, insomnia nor flask

I am trying to do a simple GET request to the Steam API:
If I do in the terminal:
curl http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/\?key\=XXXXXX\&steamids\=76561197960435530
It works:
{"response":{"players":[{"steamid":"76561197960435530","communityvisibilitystate":3,"profilestate":1,"personaname":"Robin","profileurl":"https://steamcommunity.com/id/robinwalker/","avatar":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/f1/f1dd60a188883caf82d0cbfccfe6aba0af1732d4.jpg","avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/f1/f1dd60a188883caf82d0cbfccfe6aba0af1732d4_medium.jpg","avatarfull":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/f1/f1dd60a188883caf82d0cbfccfe6aba0af1732d4_full.jpg","avatarhash":"f1dd60a188883caf82d0cbfccfe6aba0af1732d4","personastate":0,"realname":"Robin Walker","primaryclanid":"103582791429521412","timecreated":1063407589,"personastateflags":0,"loccountrycode":"US","locstatecode":"WA","loccityid":3961}]}}
However, when I type in my local browser the url, I get 404 Bad Request: "Required parameter 'key' is missing".
I though it might be related with CORS, so I tried to sent the response from a local flask application:
import requests
from flask import Flask
app = Flask(__name__)
#app.route('/')
#cross_origin()
def get_data():
return(requests.get('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/\?key\=XXXXXXX\&steamids\=76561197960435530').content)
But I also get 404 Not Found error
When you're making the request via Flask or typing it in your browser, do not escape the url yourself (if you look at the url, you will see stuff like \? and \=
Use the full url i.e.
http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=XXXXXXX&steamids=76561197960435530

How to integrate Julia with a HTML web page - how to call a Julia function from an application running in a web browser

we have a Julia language calculation engine we want to trigger on command from a HTML webpage.
How can I connect from this application to a Julia instance. Is it possible to connect to Julia via a REST service?
You just need to have Julia listening on a port for incoming requests and have it respond accordingly. You can use an HTTP package (like HTTP.jl) to easily set up a REST endpoint:
import HTTP
using Sockets
compute(req::HTTP.Request) = HTTP.Response(200, "hello world")
const SERVER = HTTP.Router()
HTTP.#register(SERVER, "GET", "/test", compute)
HTTP.serve(SERVER, ip"127.0.0.1", 12345)
Now accessing http://127.0.0.1:12345/test should show you a page with the string hello world on it.
There are many frameworks that build atop this basic paradigm.

How do I log swagger / connexion request body?

I'm using connexion and Swagger to create an API in Python. I'd like to log all of the incoming calls to a file so I can see what's being requested. I've been able to log the path of the calls I've received but I can't figure out how to log the body.
Here's where I've configured my logging:
if __name__ == '__main__':
import logging
logging.basicConfig(format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s', filename='golden_record.log',level=logging.DEBUG)
When I look into the log, I see the path, as in the following for a POST call...
2019-03-23 12:47:16,182 - werkzeug - INFO - 127.0.0.1 - - [23/Mar/2019
12:47:16] "POST /golden_record/account HTTP/1.1" 400 -
but I don't see the body of the call (i.e. the data I've sent). Is there a way to automatically record this for every call that comes in? Doing so would help debug calls that aren't functioning as desired. Thanks!
Just add a Flask before_request.
Connexion instance stores the Flask instance as the app attribute, so you can access using app.app.
Add the code and you will log the body:
#app.app.before_request
def log_request_info():
print('Body: %s', request.get_data())
Change the print method to your logger:
#app.app.before_request
def log_request_info():
logger.info('Body: %s', request.get_data())
The request import is :
from flask import request
And the app is your Connexion instance:
app = connexion.App(__name__, specification_dir="./swagger/")
I created a Gist with the code.
https://gist.github.com/kevinmmartins/f832c21215bb51cea73b8fdd28f6d88d

Admin Tools config throws 404: page not found

I try to setup the basic configuration of admin tools and fail with the url dispatcher recognizing the include of admin_tools.urls:
#urls.py
...
import admin_tools.urls
urlpatterns = patterns('',
url(r'^admintools/', include(admin_tools.urls)),
url(r'^admin/', include(admin.site.urls)),
)
#settings.py
import django.conf.global_settings as DEFAULT_SETTINGS
TEMPLATE_CONTEXT_PROCESSORS = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (
"django.core.context_processors.request",
)
INSTALLED_APPS = (
'django.contrib.auth',
...
'admin_tools',
'admin_tools.menu',
'admin_tools.dashboard',
'django.contrib.admin',
'repmgr',)
I did run syncdb. I am sure that the regexp matches /admintools/, because it works when I include another app.
The detailed error response is:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/admintools/
Using the URLconf defined in urlconf, Django tried these URL patterns, in this order:
^__debug__/m/(.*)$
^__debug__/sql_select/$ [name='sql_select']
^__debug__/sql_explain/$ [name='sql_explain']
^__debug__/sql_profile/$ [name='sql_profile']
^__debug__/template_source/$ [name='template_source']
^admin/doc/
^admintools/ ^menu/
^admintools/ ^dashboard/
^sthrep/
The current URL, admintools/, didn't match any of these.
The error message is perfectly correct :
Django tells that there is no URL pattern matching ^admintools/^. That is true. This is because django-admin-tools does not create a different admin site, but rather extends the original admin site.
The ^admintools/ pattern is only created for its sub-patterns, that provide access to pages needed by admin-tools to work well (new pages added to the original admin, for example).
By the way, in django-admin-tools documentation, at the end of the setup instructions, they say :
Congrats! At this point you should have a working installation of
django-admin-tools. Now you can just login to your admin site and see
what changed.
I guess that by your admin site they mean the standard admin site.
So I think that the good way to access your admin interface and menus and dashboards is using the standard admin.

Cannot get service account authorization to work on GCS script using Python client lib APIs

In attempting to write a python script to access GCS using service-based authorization, I have come up with the following. Note that 'key' is the contents of my p12 file.
I am attempting to just read the list of buckets on my account. I have successfully created one bucket using the web interface to GCS, and can see that with gsutil.
When I execute the code below I get a 403 error. At first I thought I was not authorized correctly, but I tried from this very useful web page (which uses web-based authorization), and it works correctly. https://developers.google.com/apis-explorer/#p/storage/v1beta1/storage.buckets.list?projectId=&_h=2&
When I look at the headers and query string and compare them to the keaders and query of the website-generated request I see that there is no authorization header, and that there is no key= tag in the query string. I suppose I thought that the credential authorization would have taken care of this for me.
What am I doing wrong?
code:
credentials = SignedJwtAssertionCredentials(
'xxx-my-long-email-from-the-console#developer.gserviceaccount.com',
key,
scope='https://www.googleapis.com/auth/devstorage.full_control')
http = httplib2.Http()
http = credentials.authorize(http)
service = build("storage", "v1beta1", http=http)
# Build the request
request = service.buckets().list(projectId="159910083329")
# Diagnostic
pprint.pprint(request.headers)
pprint.pprint(request.to_json())
# Do it!
response = request.execute()
When I try to execute I get the 403.
I got this working, however, the code I used is not fundamentally different from the snippet you posted. Just in case you'd like to diff my version with yours, attached below is a complete copy of a Python program that worked for me. I initially got a 403, just like you, which was due to inheriting your project id :). After updating that value to use my project ID, I got a correct bucket listing. Two things to check:
Make sure the project id you are using is correct and has the "Google Cloud Storage JSON API" enabled on the Google Developer Console "Services" tab (it's a different service from the other Google Cloud Storage API).
Make sure you are loading the service accounts private key exactly as it came from the developer's console. I would recommend reading it into memory from the file you downloaded, as I've done here, rather than trying to copy it into a string literal in your code.
#!/usr/bin/env python
import pprint
import oauth2client
from oauth2client.client import SignedJwtAssertionCredentials
import httplib2
from apiclient.discovery import build
f = open('key.p12', 'r')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(
'REDACTED',
key,
scope='https://www.googleapis.com/auth/devstorage.full_control')
http = httplib2.Http()
http = credentials.authorize(http)
service = build("storage", "v1beta1", http=http)
# Build the request
request = service.buckets().list(projectId="REDACTED")
# Diagnostic
pprint.pprint(request.headers)
pprint.pprint(request.to_json())
# Do it!
response = request.execute()
pprint.pprint(response)