Skip to content
Sandny Blog
  • Home
  • Java
  • JavaScript
  • AWS
  • Embedded
  • About
aws graphql with lambda AppSync

How to mutate AWS GraphQL using AWS Lambda

  • August 26, 2018September 5, 2018
  • by Coder Kai

Recently, I had to create a AWS Lambda trigger for the AWS DynamoDB table events. The tricky part on this thing was to mutate AWS GraphQL using AWS Lambda with this DynamoDB event. The reason was I wanted all the clients which were subscribed to GraphQL to get this event with modified data.

aws graphql trigger example - mutate AWS GraphQL using AWS Lambda

The problem was how to authenticate Lambda and communicate with AppSync. My mobile application was using the AWS Cognito credentials for AWS service authentication. Therefore, with the current setup I used the AWS IAM policies to authenticate the lambda function to do mutations.

Change AppSync Auth Mode to mutate AWS GraphQL using AWS Lambda

First of all, go to the AppSync and change the auth mode to AWS Identity and Access Management (IAM)

AWS AppSync Auth Mode- mutate AWS GraphQL using AWS Lambda

Furthermore, use following steps to create the lambda function.

Create IAM policy to authenticate AppSync endpoint

Go to your IAM console and create the following Policy with an appropriate name.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "appsync:GraphQL"
            ],
            "Resource": [
                "arn:aws:appsync:**-region-**:**Identity-Pool-ARN******:apis/******AppSync-API-ID***/*"
            ]
        }
    ]
}

Region: Your AWS Region:
Identity Pool ARN:
   click on edit identity pool and select Show ARN

Identity Pool ARN
AppSync Id:

AppSync ID - mutate AWS GraphQL using AWS Lambda

After creating this policy, attach it to the AWS Lambda executing role. Note that you can always give /*for your GraphQL endpoint which is the default Invocation Policy likewise.

After that, create the Lambda function which can invoke the GraphQL function. For that I used Axios library. You can use any other library option too.

const AWS = require('aws-sdk');
const axios = require('node_modules/axios/lib/axios.js');

exports.handler = async (event) => {  
    
    AWS.config.update({
      region: 'us-****-*',
      credentials: new AWS.Credentials({
         accessKeyId: "*******",
         secretAccessKey: "***********",
      })
    });

    const result = await invokeAppSync({ user1: 'dummy1', user2: 'dummy2' });
    
    console.log(result)

    return result.data;
};


const invokeAppSync = async ({ user1, user2 }) => {
    let req = new AWS.HttpRequest('https://****.appsync-api.us-****-1.amazonaws.com/graphql', 'us-****-*');
    req.method = 'POST';
    req.headers.host = '******.appsync-api.us-****-*.amazonaws.com';
    req.headers['Content-Type'] = 'multipart/form-data';
    req.body = JSON.stringify({
        "query":"mutation ($input: CreateMatchInput!) { createMatch(input: $input){  matchId } }",
            "variables": {
                "input": {
                    "matchId": "dummyid",
                    "matchUser1": user1,
                    "matchUser2": user2,
                    "timestamp":  `${Date.now()}`
                }
            }
    });

    let signer = new AWS.Signers.V4(req, 'appsync', true);
    signer.addAuthorization(AWS.config.credentials, AWS.util.date.getDate());

    const result = await axios({
        method: 'post',
        url: 'https://*******.appsync-api.us-****-*.amazonaws.com/graphql',
        data: req.body,
        headers: req.headers
    });

    return result;
});

For this lambda function, create an access key from IAM identity users. Most importantly, this access key is using for the API signing.

Finally, if you came to this point, the job is done. This will create a AppSync mutation for the lambda function and the apps will get the subscription data.

Troubleshooting

If you get the error

appsync:GraphQL write EPROTO 139686890170176:error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure:../deps/openssl/openssl/ssl/s23_clnt.c:802

Remember to correctly add https  and properly add host address in request. Remove the /graphql endpoint in the url.

If you need a way to connect the AppSync with a mobile app in a tricky situation use this tutorial: https://sandny.com/2018/06/28/create-aws-graphql-message-app/

Add a comment if you need any clarification in creating an AWS GraphQL from the AWS Lambda .

 

 

 

 

 

Use AWS GraphQL for React Native Message App
Query records for a list of keys in GraphQL AppSync AWS using VTL
Coder Kai
A humble developer
aws aws app sync aws graphql aws lambda iam credentials

Related articles

Multiple refs for an array of React Elements
Using multiple refs for an…
Immutable and Mutable Values in Javascript
07. Immutable and Mutable Values…
wrapper objects in javascript
06. Wrapper objects in Javascript
globals undefined and null values in javascript
05 Global, null and undefined…
Javascript Booleans and Equality
04. Javascript Guide Booleans and…
How to add Chakra UI Animations
Chakra UI Animations
Copy files from S3 to PostgreSQL RDS
How to copy files from…
SSL Websocket using Nginx Proxy
SSL Websocket proxy with Nginx…
Change python version correctly
Python is not setting correct…
optimize React.js load time
How to optimize React.js app…
Multiple refs for an array of React Elements
How to use IntersectionObserver to…
Multiple refs for an array of React Elements
How to dismiss dropdowns when…
Javascript guide Strings
03. Javascript Guide – Strings
How to fetch data with useEffect
How to fetch data with…
add styles to stripe elements
How to add styles to…
Typescript
How to use Typescript with…
how to optimize react-native map view
How to optimize react-native map…
debounce with react hooks
Avoid multiple clicks using debounce…
Numbers inJavascript
02. Javascript Guide – Numbers
Introduction to Javascript
01. Javascript Guide – Introduction…
41 COMMENTS
  • Mark Lloyd
    August 30, 2018 at 1:08 am
    Reply

    Very nice example

    I wish AWS would document stuff like this better.

    I’m having some difficulty working out the correct req.body for my particular schema but I’ll figure it out eventually 😉

    Just wanted to say thanks for posting this

    1. Sandaruwan Nanayakkara
      September 3, 2018 at 5:40 pm
      Reply

      Appreciate very much @disqus_QVEpRvVJRZ:disqus! Yes indeed, AWS should invest more money on documentations. At least, to make some books and distribute in kindle 😉

  • Sead-hair
    August 11, 2022 at 1:50 am
    Reply

    I’m gone to tell my little brother, that he should also pay a visit this blog on regular basis to get updated
    from most recent reports.

    Feel free to surf to my homepage: Sead-hair

  • Loorcibre
    November 12, 2022 at 8:59 pm
    Reply

    Both the patient and the doctor often don t have a high level of suspicion it is breast cancer, said Sharon Giordano, Bogler s oncologist 60mg priligy

  • desVeibia
    December 6, 2022 at 10:37 pm
    Reply

    UK Carolyn Wickware, Pharmacists unqualified to follow government switching protocols, The Pharmaceutical Journal, 10 May 2019 cialis on line

  • Xrraio
    January 6, 2024 at 3:38 am
    Reply

    types of allergy pills tablet for allergy on skin prescription vs over the counter

  • Fvdwzg
    January 9, 2024 at 2:46 am
    Reply

    top rated heartburn relief avapro 300mg cheap

  • ikaria juice reviews
    January 30, 2024 at 3:50 pm
    Reply

    I truly appreciate your technique of writing a blog. I added it to my bookmark site list and will

  • Miuehk
    January 31, 2024 at 11:23 pm
    Reply

    rybelsus 14 mg tablet rybelsus 14 mg cost rybelsus 14 mg tablet

  • Uqphaa
    February 28, 2024 at 1:37 pm
    Reply

    cyclobenzaprine 15mg drug baclofen 10mg oral baclofen 10mg uk

  • binance
    May 7, 2024 at 12:31 am
    Reply

    Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?

  • 슬롯
    June 20, 2024 at 5:47 am
    Reply

    메가 슬롯 사이트
    그가 막 말하려고 할 때 Liu Jian과 다른 사람들이 돌진했습니다.

  • binance алдым-ау коды
    September 29, 2024 at 9:14 am
    Reply

    Thanks for sharing. I read many of your blog posts, cool, your blog is very good. https://www.binance.com/sv/join?ref=PORL8W0Z

  • k8casinodaype
    November 5, 2024 at 12:29 pm
    Reply

    CR 北斗の拳6 天翔百裂


    大工の源さんブラック

    大当たりの瞬間は、周りの人と共に喜びを分かち合えるのが最高です。共感が生まれます。

    GI優駿俱樂部

    https://www.k8.boston/tags/%e3%83%93%e3%82%b8%e3%83%8d%e3%82%b9%e6%88%a6%e5%a3%ab%e3%81%ae%e8%88%9e%e5%8f%b0%e8%a3%8f
    リーチ演出が多彩で、どのタイミングで大当たりが来るかワクワクします。

    アイムジャグラーEXAnniversaryEdition

    [url=https://sites.google.com/view/cr-hokuto-no-ken-6-tensho-hya/]k8 パチンコ CR 北斗の拳6 天翔百裂
    [/url]
    CR牙狼金色になれ Ver.399 (1:1)

    魔法少女まどか☆マギカ

    CR魔法少女まどか_マギカ Ver.319

  • binance open account
    November 6, 2024 at 12:02 am
    Reply

    Thanks for sharing. I read many of your blog posts, cool, your blog is very good.

  • k8casinodaype
    November 15, 2024 at 11:15 am
    Reply

    バジリスク~甲賀忍法帖~絆2 天膳 BLACK EDITION

    CR吉宗4 天昇飛躍の極

    新しい台が出るたびにワクワクします。流行を追うのが楽しいです。

    CR びっくり戦国無双 Light Edition

    https://www.6k8k.net/2063
    演出が単純明快で、ストレスなくプレイできるのが良いです。気軽に楽しめます。

    P戦国乙女 LEGEND BATTLE

    [url=https://www.ja-securities.jp/tags/%E3%83%88%E3%83%BC%E3%83%8A%E3%83%A1%E3%83%B3%E3%83%88]オンラインカジノ[/url]
    おさるの超悟空

    イミソーレ(紫花)(赤)

    戦コレ!【泰平女君】徳川家康

  • k8casinodaype
    December 28, 2024 at 10:27 pm
    Reply

    L バイオハザード ヴェンデッタ


    4パチンコ おすすめ

    パチンコの美しいデザインの台が多く、視覚的にも楽しめます。アートとしての側面もあります。

    闘神雷電 -花田勝-

    https://www.pachinko.wiki/article/221.html
    キャラクターの個性が豊かで、ストーリーに引き込まれます。忍者の世界観が楽しめます。

    ルパン三世 ロイヤルロード金海に染まる黄金神殿

    [url=https://www.ja-securities.jp/games/id1998]
    刃牙スロット強喰[/url]
    主役は銭形

    CRサイボーグ009VSデビルマン

    CR花の慶次X~雲のかなたに~ Ver.319

    Pハイスクール・フリート

    [url=https://pachika.com/guide/post-9365.html]
    海物語3r2スペシャル 法則[/url]
    CR織田信奈の野望II

    CRぱちんこGANTZ

    P 北斗の拳 暴凶星

    L バイオハザード ヴィレッジ

    [url=https://pachika.com/news/post-5138.html]
    パチスロ リングにかけろ 新台[/url]
    GI優駿俱樂部

    北斗の拳世紀末救世主伝説

    P 北斗の拳 暴凶星

    P貞子3D2呪われた12時間

    https://www.k8casino.co.in/archives/post-526.html
    新しい台が出るたびにワクワクします。流行を追うのが楽しいです。

    CRモンスターハンタ

    https://injapan.today/topics/i-see-2
    パチンコの美しいデザインの台が多く、視覚的にも楽しめます。アートとしての側面もあります。

  • sign up binance
    January 1, 2025 at 1:40 am
    Reply

    I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  • Enregistrement à Binance
    January 30, 2025 at 5:04 pm
    Reply

    Your article helped me a lot, is there any more related content? Thanks!

  • berita dana
    February 7, 2025 at 9:29 pm
    Reply

    UID_72942561###
    Berita Hot! 🔥🔥 Isa Rachmatarwata Tersangka Kasus Jiwasraya Buntut kerugian negara hingga 16,8 Triliun! 😲😲

  • berita dana
    February 8, 2025 at 2:44 am
    Reply

    UID_53550706###
    Berita terbaru! 🔥 Isa Rachmatarwata Ditahan Kejagung dalam kasus Jiwasraya. 🚔👮‍♂️

  • berita dana
    February 8, 2025 at 10:26 am
    Reply

    UID_57092237###
    Berita gembira! 🎉 Pasokan Gas 3 Kg di Kramat Jati Kembali Normal 🎊 Siap-siap belanja gas, ya! 💪🔥

  • berita dana
    February 8, 2025 at 2:49 pm
    Reply

    UID_72339950###
    Heboh! 📣🔥 Unjuk Rasa di Polda Jatim 📢 Menuduh Jokowi Terlibat Korupsi! 😱🔍

  • berita dana
    February 8, 2025 at 6:23 pm
    Reply

    UID_27764099###
    Ini yang di ganti >>> “Bingung Kenapa 😕❓” Federasi Sepak Bola Pakistan Disanksi FIFA “Baca Penyebabnya Disini! 🧐🔍”

  • berita dana
    February 8, 2025 at 11:40 pm
    Reply

    UID_74743238###
    Ini dia! 🎉🎉 ASN BKN Ubah Pola Kerja yang baru dan efisien! 🎉🎉.

  • berita dana
    February 9, 2025 at 1:57 pm
    Reply

    UID_83344528###
    Inilah 🎉🎉 Pupuk Inovatif Kebun Riset Kujang yang bikin Wamen BUMN bangga! 💪🏻🇮🇩

  • berita dana
    February 9, 2025 at 10:10 pm
    Reply

    UID_21891068###
    Takjub 😮 dengan fenomena serbu gas? Yuk, baca Warung Tatang Diserbu Warga dan temukan faktanya! 🕵️‍♀️👀

  • slot gacor agentotoplay
    February 10, 2025 at 12:14 pm
    Reply

    UID_25978847###
    situs terbaik hanya di slot gacor agentotoplay

  • slot gacor agentotoplay
    February 10, 2025 at 6:53 pm
    Reply

    UID_95859078###
    Baru-baru ini, para pemain Mahjong Wins 3 dikejutkan dengan bocoran RTP yang diklaim bisa meningkatkan peluang kemenangan secara signifikan. Banyak yang percaya bahwa informasi ini membantu mereka mendapatkan hasil yang lebih konsisten dalam permainan. Jika Anda ingin tahu lebih lanjut, cek bocoran RTP Mahjong Wins 3 hari ini dan lihat apakah strategi ini benar-benar efektif.

  • slot gacor agentotoplay
    February 11, 2025 at 6:18 am
    Reply

    UID_57331425###
    Skandal terbaru mengguncang komunitas pecinta game slot setelah seorang admin terkenal, Rachel, dikabarkan tertangkap membocorkan pola kemenangan Gate of Olympus. Banyak yang bertanya-tanya apakah informasi ini benar-benar akurat atau hanya sekadar rumor yang beredar di kalangan pemain. Simak lebih lanjut detailnya dalam artikel admin Rachel tertangkap bocorkan pola Gate of Olympus.

  • slot gacor agentotoplay
    February 11, 2025 at 5:10 pm
    Reply

    UID_17136916###
    Kisah inspiratif datang dari seorang tukang ojek online asal Tangerang yang berhasil membawa pulang hadiah fantastis setelah bermain Mahjong Ways 2. Dengan modal kecil, ia sukses mengubah nasibnya dan meraih kemenangan besar senilai 200 juta rupiah. Penasaran bagaimana caranya? Simak kisah lengkapnya di artikel tukang ojek online menang 200 juta dari Mahjong Ways 2.

  • slot gacor agentotoplay
    February 12, 2025 at 11:49 am
    Reply

    UID_87427935###
    Cek yuk! 🚍👮‍♂️Operasi Keselamatan 2025 Polres Ciamis Siapa tahu bus favoritmu jadi sasaran! 😱👍

  • slot gacor agentotoplay
    February 13, 2025 at 2:10 am
    Reply

    UID_18563832###
    Ini yang di ganti >>> Yuk, ketahui lebih lanjut tentang Syarat Gabung OECD dan Pentingnya Ratifikasi Konvensi Antisuap di sini! 🕵️‍♀️🔎📚.

  • slot gacor agentotoplay
    February 13, 2025 at 9:49 am
    Reply

    UID_83003169###
    Kenalan yuk! 🤝 Dengan guru inspiratif ini, Guru Dede Sulaeman yang mengajarkan cara merapikan pakaian di kelasnya. 👕👚🎓

  • slot gacor agentotoplay
    February 13, 2025 at 9:26 pm
    Reply

    UID_97211224###
    Yuk, sehat bersama! 👨‍⚕️👩‍⚕️ Cek kondisi tubuh kamu di Program Cek Kesehatan Gratis sekarang juga! 💉🌡️ Selalu jaga kesehatan, ya! 🏥💖

  • indo viral
    February 14, 2025 at 5:41 am
    Reply

    UID_96794283###
    Kisah Pak Darman, OB Sekolah yang Mendadak Tajir – Nasib seseorang bisa berubah dalam sekejap! Pak Darman, seorang OB sekolah, kini tak lagi khawatir soal keuangan setelah menang 200 juta. Keberuntungannya benar-benar luar biasa

  • indo viral
    February 14, 2025 at 5:42 am
    Reply

    UID_72356120###
    strong>Dari Ojek ke Sultan, Kisah Arman yang Mendadak Kaya – Hidup Arman berubah drastis setelah keberuntungan menghampirinya. Dari seorang tukang ojek, kini ia menikmati kehidupan mewah setelah memenangkan 300 juta di Dragon Fortune. Simak kisah inspiratifnya

  • binance account creation
    February 26, 2025 at 6:16 am
    Reply

    I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  • 注册免费账户
    March 2, 2025 at 11:12 pm
    Reply

    Your point of view caught my eye and was very interesting. Thanks. I have a question for you. https://www.binance.com/en-IN/register?ref=UM6SMJM3

  • binance
    March 4, 2025 at 2:25 am
    Reply

    I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  • Inscreva-se na binance
    May 25, 2025 at 6:02 pm
    Reply

    I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • android 3
  • Apollo Client 1
  • AWS 8
    • AppSync 5
    • EC2 1
    • EKS 1
    • Route53 1
    • S3 1
  • AWS Amplify 1
  • Chakra UI 1
  • Docker 1
  • Embedded 1
  • EmberJS 1
  • FCM 1
  • Godaddy 1
  • GraphQL 3
  • ios 1
  • Jasper 1
  • Java 10
    • Java 11 1
    • Java 14 1
  • JavaEE 2
  • JavaScript 39
    • Express.js 4
    • Javascript Guide 7
    • Node.js 3
    • react-native 4
    • React.js 17
    • Typescript 1
  • Kubernetes 1
  • machine learning 1
  • Maven 2
  • OCaml 3
  • PostgreSQL 1
  • Python 2
  • react-native 4
  • ReactJS 3
  • sass 1
  • Server 6
  • spark 1
  • Terraform 2
  • Ubuntu 4
  • Uncategorized 1
  • webpack 2

Recent Comments

  • StanleySal on How to create a Vertx EventBus js client and use it with a web server with CORS
  • mejor código de referencia de Binance on Java 13 (JDK 13) -The New Features
  • Büyükçekmece su kaçak tespiti on How to create Lambda function with Terraform

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Archives

  • October 2022 3
  • September 2022 7
  • May 2022 1
  • December 2021 1
  • August 2021 1
  • July 2021 6
  • June 2021 3
  • February 2021 1
  • July 2020 1
  • December 2019 5
  • November 2019 6
  • October 2019 3
  • August 2019 1
  • March 2019 1
  • February 2019 1
  • January 2019 2
  • December 2018 1
  • September 2018 2
  • August 2018 1
  • June 2018 1
  • February 2018 1
  • November 2017 2
  • October 2017 5
  • September 2017 1
  • June 2017 1
  • May 2017 10
Sandny Blog space
Theme by Colorlib Powered by WordPress