aws-amplify / amplify-category-api

The AWS Amplify CLI is a toolchain for simplifying serverless web and mobile development. This plugin provides functionality for the API category, allowing for the creation and management of GraphQL and REST based backends for your amplify project.
https://docs.amplify.aws/
Apache License 2.0
88 stars 76 forks source link

mock rest api locally #344

Open alexladerman opened 4 years ago

alexladerman commented 4 years ago

Is your feature request related to a problem? Please describe. I want to be able to run both the frontend and backend locally, control with environment variables when to produce/consume mock data and have the urls map to the right environment. I don't use GraphQL!

Describe the solution you'd like amplify serve and mock -> frontend on localhost:3000 with env variables of mock && backend on localhost:3001 with env variables of mock

Describe alternatives you've considered writing my own bash script passing environment variables in to every backend function

attilah commented 4 years ago

@alexladerman thanks for the feature request, would you elaborate in details on your requirements, how would you imagine the developer workflow?

hisham commented 4 years ago

+1 for local mocking of API Gateway. I'm surprised this isn't supported yet by amplify mock. It would be nice to be able to run amplify mock and aws-exports.js which is consumed by our web app would automatically point to the localhost REST API rather than the cloud one.

I'm currently able to run the express server locally via amplify function invoke, but automatically changing aws-exports.js and hot reloading the express server on code change does not happen through this method.

waldothedeveloper commented 4 years ago

Add me to this list. Let's pass this bill to congress!

tim-payton commented 4 years ago

This would be really useful!

IsaacTrevino commented 4 years ago

At the moment i'm using: amplify function invoke restapiName this works pretty well. https://aws-amplify.github.io/docs/js/react#testing-serverless-functions

andre347 commented 4 years ago

+1 on this one. Would be great to quickly run amplify mock api when you have a basic rest api with express. I don't have a GraphQL backend so mock doesn't work.

Lasim commented 4 years ago

+1

AbirAbbas commented 4 years ago

we can no longer use amplify function invoke to do this, this feature would be really useful for those of us who aren't using GraphQL!

RealSlimMahdi commented 4 years ago

+1 need this functionality

hooiyung commented 4 years ago

+1 or any alternative?

AbirAbbas commented 4 years ago

Hey guys, an alternative is to cd into the src folder and run the command “node app.js” and using dotenv for local environments, this will host your function on localhost port 3000 and u can test with postman. You can also use nodemon for hot reload.

hamedmam commented 4 years ago

+1

alexkates commented 4 years ago

+1

rileyschuit commented 4 years ago

+1

AbirAbbas commented 4 years ago

hello, can we please add the old amplify function invoke flow back? this is definitely making definitely significantly more tedious as the mock functionality replaced something that was working with something that is broken...

rileyschuit commented 4 years ago

I used @AbirAbbas method and it does work. (thank you) It would be VERY NICE if I could use amplify mock api <NAME>, have aws-exports.js generate my local environment for my clientside app, and fully test. I am also thinking this would allow for easier testing in a pipeline.

dtelaroli commented 4 years ago

+1

laygir commented 4 years ago

+1

dafixios commented 4 years ago

+1

araviind0009 commented 4 years ago

+1

arturocanalda commented 4 years ago

+1

mm-ct commented 4 years ago

+1

nguyenan commented 4 years ago

+1 We are also waiting for this

deepaksingh007 commented 4 years ago

+1

Rezaavoor commented 3 years ago

in addition to @AbirAbbas workaround, for ease of development you can add a script to your main package.json file that runs the command "node app.js". package.json: "scripts": { "server_dev": "node amplify/backend/function/<function_name>/src/app.js" }

and then just run npm run server_dev

dtelaroli commented 3 years ago

This works only if you use a pure node project. If you use layers for example, it's not work.

JtawRobot commented 3 years ago

Up

tobiasriemenschneider commented 3 years ago

+1

lis10app commented 3 years ago

+1

rodrigovcortezi commented 3 years ago

+1

loganpowell commented 3 years ago

Is this why - when I submit a query to the mock api - I get:

{ errorMessage: 'Must provide Source. Received: undefined' } 

?

itachiluan commented 3 years ago

+1, since we are able to use sam local start-api to test the REST APIs locally, I think it is reasonable to assume that Amplify is able to provide something similar :)

deanbarrow commented 3 years ago

I'll share my workaround for this issue, it will allow local testing for the REST API, I've not looked into a local GraphQL API.

I just run yarn start for the frontend and yarn mock for the backend. You can also pass in events, see below.

package.json (at project root level to save changing to the function directory each time)

"scripts": {
"start": "cross-env PORT=8000 react-app-rewired start",
"mock": "nodemon amplify/backend/function/[YOUR API NAME]/src/index.js",
"mock:event": "nodemon amplify/backend/function/[YOUR API NAME]/src/index.js ./events/event.json",
}

Backend index.js

const handler = async (event, context) => {
  const awsServerlessExpress = require('aws-serverless-express')
  const app = require('./app')
  const server = awsServerlessExpress.createServer(app)

  console.log(`EVENT: ${JSON.stringify(event, null, 2)}`)

  // Express app
  return awsServerlessExpress.proxy(server, event, context, 'PROMISE').promise
}

;(async function () {
  /**
   * Support running function locally
   * ---------------------------------
   * Run `yarn mock` from project root
   * Requires `.env` in project root with:
   * - ENV=
   * - REGION=
   * - AWS_ACCESS_KEY_ID=
   * - AWS_SECRET_ACCESS_KEY=
   * - MOCK=true
   */
  if (
    process.env.npm_package_scripts_mock &&
    process.env.npm_package_scripts_mock.includes('nodemon')
  ) {
    process.env.MOCK = true
    require('dotenv').config()

    // getting the event from passed args
    const event = process.argv[2] ? require(process.argv[2]) : ''
    if (!event)
      console.log(
        `No event - run 'yarn mock:event' etc...`
      )
    const res = await handler(event, {
      done: () => {}, // err, success
    })
    if (res) console.log({ statusCode: res.statusCode, body: res.body })
  }
})()

module.exports = {
  handler,
}

React frontend

import Amplify from 'aws-amplify'
import React from 'react'
import ReactDOM from 'react-dom'

import App from './app'
import awsconfig from './aws-exports'

if (process.env.NODE_ENV === 'development') {
  awsconfig.aws_cloud_logic_custom = awsconfig.aws_cloud_logic_custom.map(
    (config) => {
      if (config.name === '[YOUR API NAME]') {
        config.endpoint = `http://${window.location.hostname}:3000`
      }
      return config
    }
  )
}
Amplify.configure(awsconfig)

ReactDOM.render(<App />, document.getElementById('root'))

Note, I've taken this code from my app and stripped it down, might need adjusting to work.

kanelincoln commented 3 years ago

+1

StefanV85 commented 3 years ago

+1 please add it!

w0wka91 commented 3 years ago

+1

agyimr commented 3 years ago

We are currently evaluating migrating away from AWS Amplify for exactly these kind of reasons. Not being able to test locally is an essential feature the lack of which drastically slows down development cycles.

rodrigowpl commented 3 years ago

I'm also having issues running locally and it's being really a pain. I'm reading the docs: https://docs.amplify.aws/cli/usage/mock

From my understanding, this only mocks the API and not the functions. Could u please recommend me clear instructions about how can I work locally?

mcmoodoo commented 3 years ago

Our team will start migrating away from 'amplify' and back to containers.

Issues like this make it impossible to develop and iterate fast!

I wouldn't say it was a waste of time though to try amplify. There are a lot of neat features, but it definitely needs more engineering force behind its development.

k3b0 commented 3 years ago

+1

SHIJILKAILAS commented 2 years ago

+1

Lasim commented 2 years ago

Still no update on this topic?

nbeuchat commented 2 years ago

+1

laygir commented 2 years ago

in case the maintainers need more +1's, here's another one, +1

derevo commented 2 years ago

Here's one more +1 :)

As a newcomer to amplify, I was surprised at the lack of this ability, but I also understand the potential complexity.

theabbie commented 2 years ago

This would be really great +1

jgverzosa commented 1 year ago

+1

danbueno20 commented 1 year ago

+1 It's fine to close duplicates, but it's frustrating when there are no comments added here in terms of whether it's even on the radar... I've definitely been finding Amplify with Python to have more issues than it's really helping with at this point.

AllanOricil commented 11 months ago

That is sad :/ I was enjoying to work with amplify After just a few hours I stumbled upon this limitation and now Im just going to give up on it