Package: lambda-proxy
lambda-proxyA zero-requirement proxy linking AWS API Gateway{proxy+}requests and AWS Lambda.Install$pipinstall-Upip
$pipinstalllambda-proxyOr install from source:$gitclonehttps://github.com/vincentsarag/lambda-proxy.git
$cdlambda-proxy
$pipinstall-Upip
$pipinstall-e.UsageLambda proxy is designed to work well with both API Gateway's REST API and the
newer and cheaper HTTP API. If you have issues using with the HTTP API, please
open an issue.With GET requestfromlambda_proxy.proxyimportAPIAPP=API(name="app")@APP.route('/test/tests/<id>',methods=['GET'],cors=True)defprint_id(id):return('OK','plain/text',id)With POST requestfromlambda_proxy.proxyimportAPIAPP=API(name="app")@APP.route('/test/tests/<id>',methods=['POST'],cors=True)defprint_id(id,body):return('OK','plain/text',id)NoteStarting in version 5.2.0, users can now add route using@APP.getand@APP.postremoving the need to addmethods=[**]Binary bodyStarting from version 5.0.0, lambda-proxy will decode base64 encoded body on POST message.Pre 5.0.0fromlambda_proxy.proxyimportAPIAPP=API(name="app")@APP.route('/test',methods=['POST']e)defprint_id(body):body=json.loads(base64.b64decode(body).decode())Post 5.0.0fromlambda_proxy.proxyimportAPIAPP=API(name="app")@APP.route('/test',methods=['POST']e)defprint_id(body):body=json.loads(body)RoutesRoute schema is simmilar to the one used inFlaskVariable parts in the route can be specified with angular brackets/user/<username>. By default a variable part in the URL accepts any string without a slash however a different converter can be specified as well by using<converter:name>.Converters:int: integerstring: stringfloat: float numberuuid: UUIDexample:/app/<user>/<id>(userandidare variables)/app/<string:value>/<float:num>(valuewill be a string, whilenumwill be a float)RegexYou can also add regex parameters descriptions using special converterregex()example:@APP.get("/app/<regex([a-z]+):regularuser>")defprint_user(regularuser):return('OK','plain/text',f"regular{regularuser}")@APP.get("/app/<regex([A-Z]+):capitaluser>")defprint_user(capitaluser):return('OK','plain/text',f"CAPITAL{capitaluser}")Warningwhen usingregex()you must use different variable names or the route might not show up in the documentation.@APP.get("/app/<regex([a-z]+):user>")defprint_user(user):return('OK','plain/text',f"regular{user}")@APP.get("/app/<regex([A-Z]+):user>")defprint_user(user):return('OK','plain/text',f"CAPITAL{user}")This app will work but the documentation will only show the second route because inopenapi.json, route names will be/app/{user}for both routes.Route Optionspath: the URL rule as stringmethods: list of HTTP methods allowed, default: ["GET"]cors: allow CORS, default:Falsetoken: setaccess_tokenvalidationpayload_compression_method: Enable and select an output body compressionbinary_b64encode: base64 encode the output body (API Gateway)ttl: Cache Control setting (Time to Live)(Deprecated in 6.0.0)cache_control: Cache Control settingdescription: route description (for documentation)tag: list of tags (for documentation)Cache ControlAdd a Cache Control header with a Time to Live (TTL) in seconds.fromlambda_proxy.proxyimportAPIAPP=API(app_name="app")@APP.get('/test/tests/<id>',cors=True,cache_control="public,max-age=3600")defprint_id(id):return('OK','plain/text',id)Note: If function returns other then "OK", Cache-Control will be set tono-cacheBinary responsesWhen working with binary on API-Gateway we must return a base64 encoded stringfromlambda_proxy.proxyimportAPIAPP=API(name="app")@APP.get('/test/tests/<filename>.jpg',cors=True,binary_b64encode=True)defprint_id(filename):withopen(f"{filename}.jpg","rb")asf:return('OK','image/jpeg',f.read())CompressionEnable compression if "Accept-Encoding" if found in headers.fromlambda_proxy.proxyimportAPIAPP=API(name="app")@APP.get('/test/tests/<filename>.jpg',cors=True,binary_b64encode=True,payload_compression_method="gzip")defprint_id(filename):withopen(f"{filename}.jpg","rb")asf:return('OK','image/jpeg',f.read())Simple Auth tokenLambda-proxy provide a simple token validation system.a "TOKEN" variable must be set in the environmenteach request must provide a "access_token" params (e.g curlhttp://myurl/test/tests/myid?access_token=blabla)fromlambda_proxy.proxyimportAPIAPP=API(name="app")@APP.get('/test/tests/<id>',cors=True,token=True)defprint_id(id):return('OK','plain/text',id)URL schema and request parametersQueryString parameters are passed as function's options.fromlambda_proxy.proxyimportAPIAPP=API(name="app")@APP.get('/<id>',cors=True)defprint_id(id,name=None):return('OK','plain/text',f"{id}{name}")requests:$curl/0000010001$curl/000001?name=vincent0001vincentMultiple Routesfromlambda_proxy.proxyimportAPIAPP=API(name="app")@APP.get('/<id>',cors=True)@APP.get('/<id>/<int:number>',cors=True)defprint_id(id,number=None,name=None):return('OK','plain/text',f"{id}-{name}-{number}")requests:$curl/0000010001--

$curl/000001?name=vincent0001-vincent-

$curl/000001/1?name=vincent0001-vincent-1Advanced featuresContext and Event passingPass event and context to the handler function.fromlambda_proxy.proxyimportAPIAPP=API(name="app")@APP.get("/<id>",cors=True)@APP.pass_event@APP.pass_contextdefprint_id(ctx,evt,id):print(ctx)print(evt)return('OK','plain/text',f"{id}")Automatic OpenAPI documentationBy default the APP (lambda_proxy.proxy.API) is provided with three (3) routes:/openapi.json: print OpenAPI JSON definition/docs: swagger html UI/redoc: Redoc html UIFunction annotationsTo be able to render full and precise API documentation, lambda_proxy uses python type hint and annotationslink.fromlambda_proxy.proxyimportAPIAPP=API(name="app")@APP.route('/test/<int:id>',methods=['GET'],cors=True)defprint_id(id:int,num:float=0.2)->Tuple(str,str,str):return('OK','plain/text',id)In the example above, our route/test/<int:id>define an inputidto be aINT, while we also add this hint to the functionprint_idwe also specify the type (and default) of thenumoption.Custom Domain and path mappingSince version 4.1.1, lambda-proxy support custom domain and path mapping (seehttps://github.com/vincentsarago/lambda-proxy/issues/16).Note: When using path mapping other thanroot(/),/route won't be available.fromlambda_proxy.proxyimportAPIapi=API(name="api",debug=True)# This route won't work when using path mapping@api.get("/",cors=True)# This route will work only if the path mapping is set to /api@api.get("/api",cors=True)defindex():html="""<!DOCTYPE html><html><header><title>This is title</title></header><body>Hello world</body></html>"""return("OK","text/html",html)@api.get("/yo",cors=True)defyo():return("OK","text/plain","YOOOOO")PluginAdd cache layer:https://github.com/vincentsarago/lambda-proxy-cacheExampleshttps://github.com/vincentsarago/lambda-proxy/tree/master/examplehttps://github.com/RemotePixel/remotepixel-tilerContribution & DevellopementIssues and pull requests are more than welcome.Dev install & Pull-Request$gitclonehttps://github.com/vincentsarago/lambda-proxy.git
$cdlambda-proxy
$pipinstall-e.[dev]Python3.7 onlyThis repo is set to use pre-commit to runmypy,flake8,pydocstringandblack("uncompromising Python code formatter") when committing new code.$pre-commitinstall
$gitadd.
$gitcommit-m'my change'black.........................PassedFlake8........................PassedVerifyingPEP257Compliance...Passedmypy..........................Passed
$gitpushoriginLicenseSeeLICENSE.txt.AuthorsSeeAUTHORS.txt.ChangesSeeCHANGES.txt.