Serverless Framework - Two services under one APIGW endpoint - microservices

If I have two services, 'Users' and 'Products', each with several functions with endpoints defined for each one (as any traditional API would), is it possible for them to be organised separately in a code base (for clarity) but once deployed share the same API base URL? For example, consider I have the following structure:
/src
-- /users
---- event.json
---- handler.js
---- serverless.yml
-- /products
---- event.json
---- handler.js
---- serverless.yml
and my src/users/serverless.yml has the following defined:
functions:
create:
handler: handler.create
events:
- http: POST user
read:
handler: handler.read
events:
- http: GET user
and my src/products/serverless.yml has basically the same thing, just swap 'user' for 'products'.
Currently, both of those services will be deployed to distinctly different API endpoints, one with a URL https://fghijklmnop.execute-api... and another with a URL https://abcdevwxyz.execute-api....
My question is, would it be possible to have these services be deployed but remain under a single API with a single URL (so both would be served under URL https://abcdevwxyz.execute-api....)?
I'm assuming the answer to be, 'No, because Cloud Formation...', but I thought I would post the question here simply for the sake of discussion and to aid my own understanding of building serverless applications.
I'm aware of using Custom Domains, as per the answer here, but for a quicker development cycle this is not really an ideal solution.
My only solution so far would be to simply create a service called 'api' which would contain all the endpoints my API would need which would simply invoke my other services' Lambda functions directly rather than via previously-configured endpoints. It would be an abstraction layer, really, but add potentially unnecessary layers to my application. Again, curious to see what the community feels on this.

You can put multiple functions in one serverless.yml
/src
-- event.json
-- users.handler.js
-- products.handler.js
-- serverless.yml

I can't speak directly to Serverless framework support, but this is certainly possible in API Gateway.
You can maintain multiple Swagger files for each "sub API", and use import?mode=merge to import both definitions into the same API.
See
http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-import-api.html
Thanks,
Ryan

What I've done with my own code is to pull all code out of the handler.js files and put it inside modules. These modules would be required into the handler.js files and a simple function would then be called.
usersModule.js:
export const doSomething = () => {
// Do something here.
};
users/handler.js:
import {doSomething} from '../.../usersModule.js';
export const handler = ( event, context, callback ) => {
doSomething();
// Do other stuff...
callback( null, "Success" );
};
This way, you can place the meat of your code wherever you would like to have it, organized in whatever way makes sense to you.
You would, however, still have to have a single API defined. Or use the answer from RyanG-AWS to merge the APIs.
If you'd still like to keep code and API definitions separate, you could create the users API and the products API separately. You would then have another combined API that would call either of these APIs. So this way, you would have a single service with a single base URL that you would call. You can do this with integration type HTTP. I have not tried this, so I don't know how well it would work.

You can use Custom Domain Names : http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-custom-domains.html
setup the custom domains name (you'll need a SSL certificate) http://myapi.com/
then map your apis :
http://myapi.com/users
http://myapi.com/products
Just call your functions like this :
http://myapi.com/users/create
http://myapi.com/users/read
http://myapi.com/products/whaterver

I came up with my own solution to this problem. I abstracted the integration points of my application so that I have specific Integration services (API, S3, SNS, etc.) which respond to events and then process those events and delegate them to separate microservices. I wrote an article on it, with code examples.

Related

AWS SAM APIGatewayProxyRequestEvent HttpMethod not set when starting API locally

I created an application with a AWS::SERVERLESS::FUNCTION, which has an HttpApi Event attached to it. I thought it would be a good idea to create one lambda per resource, so e.g. Post, Get and Put on /customer are all handled by a single lambda, which decides which action to take using
switch (input.getHttpMethod()) {
case "GET": ...
case "POST: ...
}
So now coming to my problem: When starting an application using sam local start-api my lambda gets called correctly, but neither input.getHttpMethod() nor input.getRequestContext().getHttpMethod() is set.
Given that SAM supports multiple HttpApi events, failing to provide the http method when running the application locally mitigates local development virtually completely. Am I doing something wrong, or is this really not working? I'm using Java btw, I can't tell if this problem exists using other languages as well.
Just in Case:
Is my "one lambda per resource" approach wrong, should every single action have its own lambda?
I found the problem. HttpApi uses "PayloadFormatVersion: 2.0" as default. input was of type com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent, but this represents format 1.0, I had to use com.amazonaws.services.lambda.runtime.events.APIGatewayV2HTTPEvent to get it to work.
This fails silently because instances are just constructed from json input, and several fields are the same among both classes.

VueJS SPA dynamic baseURL for axios

I've searched and searched and can't seem to find a pattern for this. I'd consider myself an intermediate Vue dev, however, the backend is my strong suit. I'm working on an app that will be white-labeled by resellers. While it's possible to have multiple builds, avoiding that would be ideal. The setup is a stand-alone vue-cli SPA connecting to a Laravel api backend and using the Sanctum auth package. So I need calls to the same domain. The issue: resellers will be on their own domain. The ask: Is there a pattern/solution for dynamically loading configs (mainly baseURL) for different domains (other items would by theme/stylesheet). Currently I have a few typical entries:
i.e. axios.defaults.baseURL = process.env.VUE_APP_API_BASE_URL
Basically, based on the domain the site is being served on, I'd like a dynamic/runtime config. I feel like this has been solved, but I can't seem to use the right search terms for some direction, so anything is helpful. I've tried a few things:
1) Parsing in js, but can't seem to get it to run early enough in the process to take effect? It seems to work, but I can't get it to "click"
2) Hit a public API endpoint with the current domain and get the config. Again, can implement, but can't seem to get it to inject into the Vue side correctly?
Any resources, pattern references or general guidance would be much appreciative to avoid maintaining multiple builds merely for a few variables. That said, I don't think there's much overhead in any of this, but also open to telling my I'm wrong and need multiple builds.
End Result
url visited is https://mydomaincom
then baseURL = https://api.mydomiancom
url visited https://resellerdomaincom
then baseURL=https://api.resellerdomaincom
I don't think there is a common pattern to solve your problem - I haven't found anything on the net.
The best software design solution could be the following:
have a single back-end
distribute only the client to your customers/resellers
Obviously the back end could see the domain of the application from which the request comes and manage the logic accordingly.
Good luck with your project.
Honestly how the question is put it's not really clear to me. Although my usual pattern is to:
Create an axios instance like so:
export const axiosInstance = axios.create({
// ...configs
baseURL: process.env.VUE_APP_URL_YOU_WOULD_LIKE_TO_HIT
})
and then whenever I make a request to some api, I would use this instance.
EDIT: According to your edit, you can either release the client to each customer, and have a .env file for each and every of them, or you can have a gateway system, where the client axios end point is always the same, hitting always the same server, and then from there the server decides what to ping, based on your own logic

Is it possible to create a second Laravel "api route" with a separate API KEY?

I'm new to Laravel and I am handed an existing application that is composed of two parts:
1 - An admin backend built on Laravel and uses Vueify
2 - The frontend website built on next.js and uses react components
The admin part communicates with Laravel using the "web routes" but also uses the "api routes" as well since the vue components make AJAX requests using those "api routes".
I am now tasked with "connecting" the frontend part to the laravel app. The frontend part will be using AJAX as well to communicate with laravel but I was told I should not use the same "api route" that is used by the admin backend because that has a lot more privileges that should not be accessible by the frontend. Basically it's a security risk and that I should somehow separate the two.
I'm not actually sure which term to use.. I initially thought it was called "channel" but I see that channel is one of the 4 "ways" of connecting to laravel (the other 3 being web, api and console). So I think routes is the term to use and forgive me for the double-quotes.
I have made a simple diagram to show the structure I mean. What I need to know is is there a way to create a second api route that would be used exclusively by the frontend and would include only a limited set of priviledges. I imagine something like /frontapi/ or /webapi/ as opposed to /api/ which is used now by the backend.
Thanks a lot for your help and please correct me if I am using wrong terminology.
EDIT
Thank you all for answering the part regarding separating the route prefix and the api route files.
One part of the question that I realized late that I hadn't made clear was the importance of separating the API Keys for both APIs since I think that is the main security issue and what would really make then two individual API "Channels or ways". I think that is one reason why I was confusing about the terminology because "way" sounded to me more separate that just a "route". I've also edited the question to reflect that. Thank you again for taking the time to help.
You can decompose routes in as many files as you want, you can also give each file its own prefix (like how api.php routes start with /api)
The modification need to be done in App\Providers\RouteServiceProvider
//in map() add $this->mapApiTwoRoutes()
public function map()
{
$this->mapApiRoutes();
$this->mapApiTwoRoutes();//<---this one
$this->mapWebRoutes();
}
//now add the method mapApiTwoRoutes
protected function mapApiTwoRoutes()
{
Route::prefix('api2')//<-- prefix in the url
->middleware('api')//<-- api middleware (throttle and such check App\Http\Kernal.php)
->namespace('App\Http\Controllers') //<-- you can modify the namespace of the controllers
->group(base_path('routes/apiTwo.php'));//<-- file containing the routes
}
And that's it.
You need to define a new route file, firstly add a new entry $this->mapApi2Routes(); in the map() function in app\Providers\RouteServiceProvider.
Then add a new function in that file, basically copying the mapApiRoutes() function, call it mapApi2Routes(). You can use different middleware etc. for the new file.
The last step would be adding a new file api2.php in the routes folder.

Where to put ajax request in Ember tutorial app?

I want to add "Weather: 24C" to the rental-listing component of the super-rentals tutorial app.
Where would be the "best-practices" place to put this ajax request?
Ember.$.getJSON(`http://api.openweathermap.org/data/2.5/weather?q=${location}&APPID=${apiKey}`)
.then(function(json) {
return JSON.parse(json).main.temp;
});
Do I need to add a component, add a model, add a service, add a second adapter, modify the existing adapter? Something else? All of these? Is the problem that the tutorial uses Mirage? I ask this because when I think I'm getting close, I get an error like this:
Mirage: Your Ember app tried to GET
'http://api.openweathermap.org/data/2.5/weather?q=london&APPID=5432',
but there was no route defined to handle this request.
Define a route that matches this path in your
mirage/config.js file. Did you forget to add your namespace?
You need to configure mirage to allow you making calls to outside in case mirage is active; what I mean is using this.passthrough function within mirage/config.js, that is explained in api documentation quite well.
Regarding your question about where to make the remote call is; it depends:
If you need the data from the server to arrive in case a route is about to open; you should prefer putting it within model hook of the corresponding route.
If you intend to develop a component that is to be reused from within different routes or even from within different applications with the same remote call over and over again; you can consider putting the ajax remote call to a component. Even if that is not a very common case usually; it might be the case that a component itself should be wrapped up to fetch the data and display it by itself for reusing in different places; there is nothing that prevents you to do so. However by usually applying data-down action-up principle; generally the remote calls fall into routes or controllers.
Whether using an ember-data model is another thing to consider. If you intend to use ember-data; you should not directly use Ember.$.ajax but rather be using store provided by ember-data and perhaps providing your custom adapter/serializer to convert data to the format ember-data accepts in case the server do not match to the formats that ember-data accepts. In summary; you do not need to use models if you use pure ajax as you do in this question.

Serverless deploying multiple functions

I've recently updated my serverless project, and I've found that many things have changed in the last few updates.
https://serverless.com/
I don't fully understand whats the correct way to have multiple lambda functions and api gateway endpoints related to the same project. With the old serverless I have every lambda and endpoint as a completely seperate function, this worked pretty well for me.
I can't seem to do this anymore, if I try my second lambda function overrides my first, presumably because my "service name" for both is the same. My service name is the same because I want both rest endpoints in the same API in API Gateway. Since serverless creates the API name based on the service name.
So then I tried to add both functions to the same "Service". this worked for the most part, except that now I need to include my custom role statement for all my functions into the same role (because this one role is now being linked to all my functions). Effectively giving more permissions to each individual function than it should have. The other issue is that all my handler files for the different functions are being put into each functions deployment bundle.
So basically, I'm not sure what is the correct approach to have multiple functions that relate to the same project but are separate in functionality. It used to make sense, now doesn't.
If anybody can give me some pointers please
Thanks
I understand your frustration. I had the same feeling until I looked deeper into the new version and formed a better understanding. One thing to note though, is the new version is not completely finished yet. So if something is completely missing, you can file an issue and have it prioritized before 1.0 is out.
You are supposed to define multiple functions under the same service under the functions: section of serverless.yml. To package these functions individually (exclude code for other functions) you will have to set individually: true under package: section. You can then use include and exclude options at the root level and at the function level as well. There's an upcoming change that will let you use glob syntax in your include and exclude options (example **/*-fn.js). You can find more about packaging here https://www.serverless.com/framework/docs/providers/aws/guide/deploying.
Not sure how to use different roles for different functions under the same service.. How did you do it with 0.5?
I was trying to find a solution for individual iam roles per function as well. I couldn't find a way to do it, but while I was looking through the documentation I found the line: "Support for separate IAM Roles per function is coming soon." on this page, so at least we know they are working on it.
The "IAM Roles Per Function" plugin for Serverless allows you to do exactly what it says on the tin: specify roles for each function. You can still use the provider-level roles as well:
By default, function level iamRoleStatements override the provider level definition. It is also possible to inherit the provider level definition by specifying the option iamRoleStatementsInherit: true
EDIT: You can also apply a predefined AWS role at both the provider and function level.

Resources