Tyk - request body is forwarded without being transformed - tyk

I am new to api gateways and I wanted to try to use Tyk product
I installed the docker version and created an api using the documentation
I tried to do a transformation using templates but the request was forwarded without any transformation
here is the Api configuration
{
"name": "Hello-World",
"slug": "hello-world",
"api_id": "Hello-World",
"org_id": "1",
"use_keyless": true,
"auth": {
"auth_header_name": "Authorization"
},
"definition": {
"location": "header",
"key": "x-api-version"
},
"version_data": {
"not_versioned": true,
"versions": {
"Default": {
"name": "Default",
"use_extended_paths": true
},
"extended_paths": {
"transform": [
{
"path": "/widgets",
"method": "POST",
"template_data": {
"template_mode": "file",
"template_source": "./templates/transform_test.tmpl"
}
}
]
}
}
},
"proxy": {
"listen_path": "/widgets",
"target_url": "http://7857-102-158-57-156.ngrok.io/api/v1",
"strip_listen_path": true
},
"active": true
}
The target_url is pointing to dummy express service that responds with the request body.
here is the template I am using
{
"value1": "{{.value2}}",
"value2": "{{.value1}}",
"transformed_list": [
{{range $index, $element := .value_list}}
{{if $index}}
, "{{$element}}"
{{else}}
"{{$element}}"
{{end}}
{{end}}
]
}
and this is the input I am trying to transform
{
"value1": "value-1",
"value2": "value-2",
"value_list": [
"one",
"two",
"three"
]
}

There seems to be an issue with your API definition file. The extended_paths section should be a child of the Default field. This is what it should look like
{
"version_data": {
"not_versioned": true,
"versions": {
"Default": {
"name": "Default",
"use_extended_paths": true,
"extended_paths": {
"transform": [
{
"path": "/widgets",
"method": "POST",
"template_data": {
"template_mode": "file",
"template_source": "./templates/transform_test.tmpl"
}
}
]
}
}
}
}
}

Related

error 403 when i post create request to openstack with restapi , how to fix?

I'm trying to do a post request for creating a server in the openstack using REST API. I tried this code (followed in the Openstack documentation) but it response 403 error code
request for token
{ "auth":
{ "identity":
{ "methods": ["password"],
"project": "7646jkkjds876tdsuhi87fd4d2a953ca3f4",
"password":
{"user":
{"domain":{"name": "default"},
"name": "test",
"password": "zxcZXC123#"
}
}
}
}
}
and my Request for creating the Server
{
"server": {
"name": "test-vm1",
"imageRef": "c8d859c9-ce15-4673-a486-5524ba1e41ff",
"flavorRef": "0",
"max_count": 1,
"min_count": 1,
"networks": [
{
"uuid": "01f1888b-1d12-4e6c-9936-d8175e71f311"
}
],
"security_groups": [
{
"name": "default"
}
]
}
}
please help me
I found the answer. This error is shown when you don't send the project scope in the API token. I corrected my JSON like this and it's done.
{ "auth": {
"identity": {
"methods": ["password"],
"password": {
"user": {
"name": "test",
"domain": { "id": "default" },
"password": "zxcZXC123"
}
}
},
"scope": {
"project": {
"name": "test",
"domain": { "id": "default" }
}
}
}
}

NLog webservice target how do I specify json layout in appsettings.json

I can't seem to find an example. I want to Use NLog as a webservice, but when I add it I am seeing HTTP POST with a body of {}. How in appsettings.json do I specify the json layout?
"NLog": {
"targets": {
"allfile":{
"type":"File",
"fileName":"/tmp/nlog-all-${shortdate}.log",
"layout":"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"
},
"dabomb": {
"type": "webservice",
"url": "http://localhost:9990/api/foo/",
"protocol": "JsonPost",
????? WHAT GOES HERE ??????
}
},
"rules": [
{
"logger": "*",
"minLevel": "Debug",
"writeTo": "dabomb"
}
]
You can try this:
"dabomb": {
"type": "webservice",
"url": "http://localhost:9990/api/foo/",
"protocol": "JsonPost",
"parameters": [
{
"Name": "",
"Layout": {
"type": "JsonLayout",
"Attributes": [
{
"name": "level",
"layout": "${level}"
},
{
"name": "message",
"layout": "${message}"
} ]
}
} ]
}
See also: https://github.com/NLog/NLog/wiki/WebService-target

Logic App with azure monitor and conditions

I create a workflow with logicAPP. The goal is to notify a team when patch is missing for VM. I use azure monitor in the logic app to set the query. I decided to put after the Azure Monitor , a condition to know if the query table is empty or have data. if the table is empty, the logix is true , so it does'nt send notification, and when its false , it sends notification.
When I run , I got a logic errors. Normally , the table has not data but after condition , the function empty([my_table]) returns false and sends me notification with the result ("The query yielded no data")
what is the problem ??
Thanks
Based on the above shared requirement we have created the logic app & tested it our local environment , it is working fine.
Below is the complete logic code :
{
"definition": {
"$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
"actions": {
"Condition_2": {
"actions": {
"Terminate_2": {
"inputs": {
"runStatus": "Cancelled"
},
"runAfter": {},
"type": "Terminate"
}
},
"else": {
"actions": {
"Send_an_email_(V2)_2": {
"inputs": {
"body": {
"Body": "<p>#{base64ToString(body('Run_query_and_visualize_results')?['body'])}</p>",
"Subject": "list of vm from update management ",
"To": "<UserEmailId>"
},
"host": {
"connection": {
"name": "#parameters('$connections')['office365']['connectionId']"
}
},
"method": "post",
"path": "/v2/Mail"
},
"runAfter": {},
"type": "ApiConnection"
}
}
},
"expression": {
"and": [
{
"equals": [
"#length(body('Run_query_and_visualize_results')?['body'])",
0
]
}
]
},
"runAfter": {
"Run_query_and_visualize_results": [
"Succeeded"
]
},
"type": "If"
},
"Run_query_and_visualize_results": {
"inputs": {
"body": "Update\n| where Classification == 'Security Updates' or Classification == 'Critical Updates'\n| where UpdateState == 'Needed'\n| summarize by Computer,ResourceGroup,Classification,UpdateState\n|sort by Computer",
"host": {
"connection": {
"name": "#parameters('$connections')['azuremonitorlogs']['connectionId']"
}
},
"method": "post",
"path": "/visualizeQuery",
"queries": {
"resourcegroups": "<Resource_group_Name",
"resourcename": "<log analytics workspacename",
"resourcetype": "Log Analytics Workspace",
"subscriptions": "<subcription_id>",
"timerange": "Last 12 hours",
"visType": "Html Table"
}
},
"runAfter": {},
"type": "ApiConnection"
}
},
"contentVersion": "1.0.0.0",
"outputs": {},
"parameters": {
"$connections": {
"defaultValue": {},
"type": "Object"
}
},
"triggers": {
"Recurrence": {
"evaluatedRecurrence": {
"frequency": "Hour",
"interval": 3
},
"recurrence": {
"frequency": "Hour",
"interval": 3
},
"type": "Recurrence"
}
}
},
"parameters": {
"$connections": {
"value": {
"azuremonitorlogs": {
"connectionId": "/subscriptions/<subcription-id>/resourceGroups/<resource-group>/providers/Microsoft.Web/connections/azuremonitorlogs",
"connectionName": "azuremonitorlogs",
"id": "/subscriptions/<subcription-id>/providers/Microsoft.Web/locations/northcentralus/managedApis/azuremonitorlogs"
},
"office365": {
"connectionId": "/subscriptions/<subcription-id>/resourceGroups/<resource-group>/providers/Microsoft.Web/connections/office365",
"connectionName": "office365",
"id": "/subscriptions/<subcription-id>/providers/Microsoft.Web/locations/northcentralus/managedApis/office365"
}
}
}
}
}
please find the reference output of the above logic sample run :

Pass an already existing Model to next in Loopback

There is Project model
{
"name": "Project",
"plural": "Projects",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"title": {
"type": "string",
"required": true
},
"description": {
"type": "string"
},
"code": {
"type": "string"
},
"startDate": {
"type": "date",
"required": true
},
"endDate": {
"type": "date"
},
"value": {
"type": "number"
},
"infoEN": {
"type": "string"
},
"infoRU": {
"type": "string"
},
"infoAM": {
"type": "string"
},
"externalLinks": {
"type": [
"string"
]
}
},
"validations": [],
"relations": {
"industry": {
"type": "belongsTo",
"model": "Industry",
"foreignKey": "",
"options": {
"nestRemoting": true
}
},
"service": {
"type": "belongsTo",
"model": "Service",
"foreignKey": "",
"options": {
"nestRemoting": true
}
},
"tags": {
"type": "hasAndBelongsToMany",
"model": "Tag",
"foreignKey": "",
"options": {
"nestRemoting": true
}
}
},
"acls": [],
"methods": {}
}
And it hasAndBelongsToMany tags
here is Tag model
{
"name": "Tag",
"plural": "Tags",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"name": {
"type": "string",
"required": true
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
Now when the relation is created loopback api gives this api endpoint.
POST /Projects/{id}/tags
This creates a new tag into the tags collection and adds it to the project.
But what about adding an already existing tag to the project?
So I figured maybe I add before save hook to the Tag
Here I'll check if the tag exists and then pass the existing one for the relation.
Something like this.
tag.js
'use strict';
module.exports = function(Tag) {
Tag.observe('before save', function(ctx, next) {
console.log(ctx.instance);
Tag.find({name: ctx.instance.name})
next();
});
// Tag.validatesUniquenessOf('name', {message: 'name is not unique'});
};
#HaykSafaryan it just demo to show you how to use tag inside project
var app = require('../../server/server');
module.exports = function(project) {
var tag=app.models.tags
//afterremote it just demo. you can use any method
project.afterRemote('create', function(ctx, next) {
tag.find({name: ctx.instance.name},function(err,result)){
if(err) throw err;
next()
}
});
};
this is just example code to show you how to use update,create ,find ,upsertwithwhere etc. tag for validation you have to setup condition over here it will not take validation which you defined in tags models

Can we declare stage name inside the template.serverless file?

We are creating AWS Serverless Lambda function using .NET Core. When we deploy this lambda function it added automatically "Prod" suffix in the url. But we want change it to "dev". Can we declare stage name inside the serverless.template file?
Here is my serverless.template file:
{
"AWSTemplateFormatVersion" : "2010-09-09",
"Transform" : "AWS::Serverless-2016-10-31",
"Description" : "An AWS Serverless Application that uses the ASP.NET Core framework running in Amazon Lambda.",
"Parameters" : {
},
"Conditions" : {
},
"Resources" : {
"Get" : {
"Type" : "AWS::Serverless::Function",
"Properties": {
"Handler": "F2C.MAP.API.AWSLambda.PublicAPI::F2C.MAP.API.AWSLambda.PublicAPI.LambdaEntryPoint::FunctionHandlerAsync",
"Runtime": "dotnetcore2.0",
"CodeUri": "",
"MemorySize": 256,
"Timeout": 30,
"Role": null,
"Policies": [ "AWSLambdaFullAccess" ],
"Environment" : {
"Variables" : {
}
},
"Events": {
"PutResource": {
"Type": "Api",
"Properties": {
"Path": "/{proxy+}",
"Method": "GET"
}
}
}
}
},
"POST" : {
"Type" : "AWS::Serverless::Function",
"Properties": {
"Handler": "F2C.MAP.API.AWSLambda.PublicAPI::F2C.MAP.API.AWSLambda.PublicAPI.LambdaEntryPoint::FunctionHandlerAsync",
"Runtime": "dotnetcore2.0",
"CodeUri": "",
"MemorySize": 256,
"Timeout": 30,
"Role": null,
"Policies": [ "AWSLambdaFullAccess" ],
"Environment" : {
"Variables" : {
}
},
"Events": {
"PutResource": {
"Type": "Api",
"Properties": {
"Path": "/{proxy+}",
"Method": "POST"
}
}
}
}
}
},
"Outputs" : {
}
}
We are using AWS Toolkit for visual studio 2017 to deploy aws serverless lambda.("https://aws.amazon.com/blogs/developer/preview-of-the-aws-toolkit-for-visual-studio-2017")
The only way I could find to make this work is the specify a AWS::Serverless::Api to use. The following example sets both the StageName and the ASPNETCORE_ENVIRONMENT to the EnvironmentName parameter.
serverless.template:
{
"AWSTemplateFormatVersion" : "2010-09-09",
"Transform" : "AWS::Serverless-2016-10-31",
"Description" : "An AWS Serverless Application that uses the ASP.NET Core framework running in Amazon Lambda.",
"Parameters" : {
"EnvironmentName" : {
"Type" : "String",
"Description" : "Sets the ASPNETCORE_ENVIRONMENT variable as well as the API's StageName to this.",
"MinLength" : "0"
}
},
"Resources" : {
"ProxyFunction" : {
"Type" : "AWS::Serverless::Function",
"Properties": {
"Handler": "PeopleGateway::PeopleGateway.LambdaEntryPoint::FunctionHandlerAsync",
"Runtime": "dotnetcore2.0",
"CodeUri": "",
"MemorySize": 256,
"Timeout": 30,
"Role": null,
"Policies": [ "AWSLambdaFullAccess", "AWSLambdaVPCAccessExecutionRole" ],
"Environment" : {
"Variables" : {
"ASPNETCORE_ENVIRONMENT": { "Ref" : "EnvironmentName" }
}
},
"Events": {
"PutResource": {
"Type": "Api",
"Properties": {
"Path": "/{proxy+}",
"Method": "ANY",
"RestApiId": { "Ref": "APIGateway" }
}
}
}
}
},
"APIGateway": {
"Type" : "AWS::Serverless::Api",
"Properties": {
"StageName": { "Ref" : "EnvironmentName" },
"DefinitionBody": {
"swagger": "2.0",
"info": {
"title": {
"Ref": "AWS::StackName"
}
},
"paths": {
"/{proxy+}": {
"x-amazon-apigateway-any-method": {
"x-amazon-apigateway-integration": {
"httpMethod": "POST",
"type": "aws_proxy",
"uri": {
"Fn::Sub": "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${ProxyFunction.Arn}/invocations"
}
},
"responses": {}
}
}
}
}
}
}
},
"Outputs" : {
"ApiURL" : {
"Description" : "API endpoint URL for the specified environment",
"Value" : { "Fn::Sub" : "https://${APIGateway}.execute-api.${AWS::Region}.amazonaws.com/${EnvironmentName}/" }
}
}
}