10 ways to build applications faster with Amazon CodeWhisperer

Amazon CodeWhisperer is a powerful generative AI tool that gives me coding superpowers. Ever since I have incorporated CodeWhisperer into my workflow, I have become faster, smarter, and even more delighted when building applications. However, learning to use any generative AI tool effectively requires a beginner’s mindset and a willingness to embrace new ways of working.

Best practices for tapping into CodeWhisperer’s power are still emerging. But, as an early explorer, I’ve discovered several techniques that have allowed me to get the most out of this amazing tool. In this article, I’m excited to share these techniques with you, using practical examples to illustrate just how CodeWhisperer can enhance your programming workflow. I’ll explore:

Typing less
Generating functions using code
Generating functions using comments
Generating classes
Implementing algorithms
Writing unit tests
Creating sample data
Simplifying regular expressions
Learning third-party code libraries faster
Documenting code

Before we begin

If you would like to try these techniques for yourself, you will need to use a code editor with the AWS Toolkit extension installed. VS Code, AWS Cloud9, and most editors from JetBrains will work. Refer to the CodeWhisperer “Getting Started” resources for setup instructions.

CodeWhisperer will present suggestions automatically as you type. If you aren’t presented with a suggestion, you can always manually trigger a suggestion using the Option + C (Mac) or Alt + C (Windows) shortcut. CodeWhisperer will also sometimes present you with multiple suggestions to choose from. You can press the → and ← keys to cycle through all available suggestions.

The suggestions CodeWhisperer offers are non-deterministic, which means you may receive slightly different suggestions than the ones shown in this article. If you receive a suggestion that doesn’t suit your needs, try cycling through all available suggestions using the arrow keys or try rephrasing any code comment prompts slightly. Even punctuation changes can produce fresh suggestions.

The examples in this article are written in JavaScript and TypeScript. However, the techniques I’ll demonstrate are equally suited to many of the programming languages supported by CodeWhisperer. Now, onto the examples!

Typing less

At the most basic level, CodeWhisperer can be used as a supercharged auto-complete, significantly reducing your typing when writing individual lines or blocks of code. To use CodeWhisperer in this way, just write code as you normally would. CodeWhisperer will make automatic suggestions as you type. Accept suggestions when they’re helpful, and ignore suggestions when they’re not. In my experience, using CodeWhisperer in this way alone reduces my typing by 50% or more.

Generating functions

Automatically generating function bodies from signatures

Skilled programmers use clear, descriptive names for their functions and parameters. If you follow this practice in your own programming, CodeWhisperer will have all the context it needs to implement many functions for you.

After I enter the function signature below, CodeWhisperer generates the function body for me.

User input (JavaScript):

function standardDeviation(numbers)

Result:

function standardDeviation(numbers) {
let mean = numbers.reduce((a, b) => a + b) / numbers.length;
let variance =
numbers.reduce((a, b) => a + Math.pow(b – mean, 2)) / numbers.length;
return Math.sqrt(variance);
}

Generating functions from comments

Sometimes a good function signature alone isn’t enough to convey the desired behavior of a function. In those cases, you can use a detailed code comment as a prompt to CodeWhisperer. I recommend using your language’s doc comment delimiter when using this technique.

User Input (JavaScript):

/**
* Given a list that contains some numbers and strings, format them into a string
* in which the numbers are prepended with “#” and the strings are wrapped in
* double quotes.
*/

Result:

/**
* Given a list that contains some numbers and strings, format them into a string
* in which the numbers are prepended with “#” and the strings are wrapped in
* double quotes.
*/
function formatList(list) {
return list
.map((item) => {
if (typeof item === “number”) {
return `#${item}`;
} else {
return `”${item}”`;
}
})
.join(“, “);
}

Generating classes

You can generate full or partial class implementations from a single code comment. The comment should describe the key properties and behaviors of the class. Simple descriptions are often all that is required.

User input (TypeScript):

/**
* A folder has a name, children, and an optional parent. A child can’t be added
* twice.
*/

Result:

After I write the above block comment, CodeWhisperer provides multiple suggestions, including the following implementation, complete with documentation comments for each method!

/**
* A folder has a name, children, and an optional parent. A child can’t be added
* twice.
*/
export class Folder {
name: string;
children: Folder[];
parent?: Folder;

constructor(name: string, parent?: Folder) {
this.name = name;
this.children = [];
this.parent = parent;
}

/**
* Add a child to the folder.
* @param child The child to add.
* @returns True if the child was added, false if it was already present.
*/
addChild(child: Folder): boolean {
if (this.children.includes(child)) {
return false;
}
this.children.push(child);
child.parent = this;
return true;
}

/**
* Remove a child from the folder.
* @param child The child to remove.
* @returns True if the child was removed, false if it wasn’t present.
*/
removeChild(child: Folder): boolean {
const index = this.children.indexOf(child);
if (index === -1) {
return false;
}
this.children.splice(index, 1);
child.parent = undefined;
return true;
}
}

Implementing algorithms

CodeWhisperer enables you to implement well-known algorithms with ease. Simply tell CodeWhisperer which algorithm you want to apply to a particular coding problem, and it will oblige.

User input (JavaScript):

const actors = [ … ];

// Sort the actors by age using the merge sort algorithm.

Result:

const actors = [ … ];

// Sort the actors by age using the merge sort algorithm.
function mergeSort(arr) {
if (arr.length < 2) {
return arr;
}

const middle = Math.floor(arr.length / 2);
const left = arr.slice(0, middle);
const right = arr.slice(middle);

return merge(mergeSort(left), mergeSort(right));
}

function merge(left, right) {
const result = [];

while (left.length && right.length) {
if (left[0].age < right[0].age) {
result.push(left.shift());
} else {
result.push(right.shift());
}
}

while (left.length) {
result.push(left.shift());
}

while (right.length) {
result.push(right.shift());
}

return result;
}

console.log(mergeSort(actors));

Writing unit tests

CodeWhisperer accelerates the implementation of unit tests. Not only is it able to implement the logic for most of the explicit unit tests I ask for, but it often suggests unit tests for edge cases that hadn’t even occurred to me.

When I want CodeWhisperer to implement a unit test, I start with a declaration of the condition I’m testing and the expected result as in the following example.

User input (JavaScript):

describe(“Folder.addChild()”, () => {
it(“when adding an existing folder should not add duplicate”

Result:

describe(“Folder.addChild()”, () => {
it(“when adding an existing folder should not add duplicate”, () => {
const folder = new Folder(“root”);
const child = new Folder(“child”);
folder.addChild(child);
folder.addChild(child);
expect(folder.children.length).toBe(1);
});
});

After you’ve written a test or two, CodeWhisperer is likely to suggest more tests, even without explicit prompting.

Tip: You’ll notice that my test description includes 1) the function I’m testing, 2) the condition I’m testing, and 3) what I expect the result to be. Following this three-part pattern is a great way to ensure CodeWhisperer has the context it needs to implement high quality test logic.

Creating sample data

One of the delightful discoveries I’ve made is that CodeWhisperer can generate dummy data—or really any code that has a repeating pattern. As an illustration, for the following list I entered only the first “user” object as an example, and CodeWhisperer helpfully continued the pattern.

User input (JavaScript):

const fakeUsers = [
{ name: “User 1”, id: “user1” },

Result:

const fakeUsers = [
{ name: “User 1”, id: “user1” },
{ name: “User 2”, id: “user2” },
{ name: “User 3”, id: “user3” },
{ name: “User 4”, id: “user4” },
{ name: “User 5”, id: “user5” },
{ name: “User 6”, id: “user6” }
]

It even works for generating random but plausible values like the names seen below.

User input (JavaScript):

const fakeUsers = [
{ name: “Sally”, id: “user1” },

Result:

const fakeUsers = [
{ name: “Sally”, id: “user1” },
{ name: “Bob”, id: “user2” },
{ name: “Joe”, id: “user3” },
{ name: “Jane”, id: “user4” },
{ name: “Jill”, id: “user5” },
{ name: “Jack”, id: “user6” }
]

Simplifying regular expressions

While CodeWhisperer can’t translate natural language into custom regular expressions (yet), it does know a lot of commonly used regular expressions. This saves you time by putting these regular expressions at your fingertips whenever you need them.

Let’s look at one notoriously complex but common regular expression.

User input (JavaScript):

/**
* Function that validates whether a string is a valid email address.
*/

Result:

/**
* Function that validates whether a string is a valid email address.
*/
function validateEmail(email: string): boolean {
const re =
/^(([^<>()[]\.,;:s@”]+(.[^<>()[]\.,;:s@”]+)*)|(“.+”))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}

Learning third-party code libraries faster

CodeWhisperer helps accelerate my learning when I’m using an unfamiliar library, module, or framework. In the example below, I needed to write a utility function that would take a gzip compressed value coming from an API and translate it into a value that the rest of my code could understand. I knew the “pako” library would help me, but I had no idea how to use it. I just prompted CodeWhisperer with an import statement and a comment describing my goal.

import pako from “pako”;

/**
* Accepts a base64-encoded, gzip-compressed JSON string and returns
* a parsed JSON object.
*/

Result:

import pako from “pako”;

/**
* Accepts a base64-encoded, gzip-compressed JSON string and returns
* a parsed JSON object.
*/
export function decodeGzipJson(base64String) {
const compressed = atob(base64String);
const uncompressed = pako.inflate(compressed, { to: “string” });
return JSON.parse(uncompressed);
}

Documenting code

CodeWhisperer is capable of generating docstrings and comments for the code it generates, as well as for your existing code. For example, let’s say I want CodeWhisperer to document the matches() method of this FavoritesFilter TypeScript class I’ve implemented (I’ve omitted some implementation details for brevity).

class FavoritesFilter implements IAssetFilter {

matches(asset: Asset): boolean {

}
}

I can just type a doc comment delimiter (/** */) immediately above the method name and CodeWhisperer will generate the body of the doc comment for me.

Note: When using CodeWhisperer in this way you may have to manually trigger a suggestion using Option + C (Mac) or Alt + C (Windows).

class FavoritesFilter implements IAssetFilter {

/**
* Determines whether the asset matches the filter.
*/
matches(asset: Asset): boolean {

}
}

Conclusion

I hope the techniques above inspire ideas for how CodeWhisperer can make you a more productive coder. Install CodeWhisperer today to start using these time-saving techniques in your own projects. These examples only scratch the surface. As additional creative minds start applying CodeWhisperer to their daily workflows, I’m sure new techniques and best practices will continue to emerge. If you discover a novel approach that you find useful, post a comment to share what you’ve discovered. Perhaps your technique will make it into a future article and help others in the CodeWhisperer community enhance their superpowers.

Kris Schultz (he/him)

Kris Schultz has spent over 25 years bringing engaging user experiences to life by combining emerging technologies with world class design. In his role as 3D Specialist Solutions Architect, Kris helps customers leverage AWS services to power 3D applications of all sorts.

Bringing JavaScript to WebAssembly

#​625 — February 10, 2023

Read on the Web

It looked quiet at first but wow, what an epic week this turned out to be. There’s a lot to chew on here, and we even have a variety of bonus items at the very end of the issue. Enjoy!
__
Your editor, Peter Cooper

JavaScript Weekly

Speeding Up the JS Ecosystem: It’s ESLint’s Turn — Last year we featured an article from the same author about how he was finding, and fixing, low-hanging performance fruit in popular JavaScript projects. He’s back, and he’s found a lot of potential for savings in ESLint this time.

Marvin Hagemeister

The Future (and the Past) of the Web is Server Side Rendering — It’s fair to say the Deno folks have some skin in this game, but nonetheless this is a neat brief history of server-side rendering and why they feel it’s the right approach for modern web development.

Andy Jiang (Deno)

Monitoring Your NestJS Application with AppSignal — With AppSignal, you can monitor your NestJS app with ease and rely on OpenTelemetry to handle third-party instrumentations. AppSignal even provides helper functions to help you build comprehensive custom instrumentation. A box of ? included!

AppSignal sponsor

Ten Web Development Trends in 2023 — Following the State of JS survey results Robin takes a considered look at new web dev trends that we should be paying attention to this year, and why they matter.

Robin Wieruch

Bringing JavaScript to WebAssembly for Shopify Functions — As much as this is focused on a specific use case at Shopify, this is a fascinating look at how they’re integrating JavaScript and WebAssembly under tight constraints. They also talk about Javy, a JS to WebAssembly toolchain being built at Shopify that lets you run JS code on a WASM-embedded JS runtime.

Surma (Shopify)

Google Touts Web-Based Machine Learning with TensorFlow.js

Richard MacManus (The New Stack)

IN BRIEF:

? Time to celebrate — a recent survey allegedly found that JavaScript applications ‘have fewer flaws’ than Java and .NET ones. So there you go.

Honeypot’s highly anticipated ▶️ React.js documentary drops later today – it’ll probably be out by the time you read this.

Vanilla List is a directory of ‘vanilla’ JavaScript controls and plugins.

▶️ Evan You tells us what to expect in 2023 from Vue.js.

The Scala.js project is celebrating its ten year anniversary – it’s now a mature way to build Web projects using Scala, if you prefer.

? Vue.js Live is a JavaScript event taking place both in London and online on May 12 & 15. From the same folks as the also forthcoming JSNation conference.

A history of criticisms levelled at React.

RELEASES:

Eleventy / 11ty 2.0
↳ Popular Node.js static site generator.

pnpm 7.27 – The efficient package manager.

RxDB 14.0 – Offline-first, reactive database.

? Articles & Tutorials

Design Patterns in TypeScript — OO-inspired patterns aren’t for everyone or every use case, but this is a fantastic catalog of examples, complete with diagrams and explanations, if you need to learn to tell apart factory methods from decorators, facades, or proxies.

Refactoring Guru

Resumable React: How To Use React Inside Qwik — Building React apps without ever loading React in the user’s browser? “Sounds too good to be true? Let’s see how this works.”

Yoav Ganbar

Did You Know That You’re Already a Distributed Systems Developer?

Temporal Technologies sponsor

Build a Hacker News Client using Alpine.jsAlpine.js is a thin and elegant reactivity library that lets you add dynamic functionality to your site directly in markup. This is a short and sweet practical example of what you can quickly do with it.

Salai Vedha Viradhan

▶  TypeScript Speedrun: A Crash Course for Beginners — If you want to pick up TypeScript and would find a video guide useful, this is for you. Matt has become well known recently for his educational TypeScript tweets and videos, and this is another good one that flies through the basics. (23 minutes.)

Matt Pocock

Using Notion as a Headless CMS with Nuxt

Trent Brew

The Options API vs Composition API in Vue.js

Charles Allotey

? Code & Tools

Bookmarklet Editor: Easily Work on JavaScript Bookmarklets — Useful because who can remember the exact syntax for a bookmarklet? ? This also can instantly convert code to and from bookmarklet form and includes some examples in the help section (click the big ? to get all the details).

Marek Gibney

Breakpoints and console.log Is the Past, Time Travel Is the Future — 15x faster JavaScript debugging than with breakpoints and console.log, now with support for Vitest.

Wallaby.js sponsor

Yup 1.0: Super Simple Object Schema Validation — Define a schema, transform a value to match, assert the shape of an existing value, or both. Very extensive docs here.

Jason Quense

Material React Table: A Full-Featured React Table Component — Built upon Material UI 5 and TanStack Table 8. The docs include lots of interactive examples.

Kevin Van Cott

BlockNote: Notion-Style Block-Based Text Editor — Built on top of Prosemirror and Tiptap, this is for you if you like the way the Notion note-taking service’s text editor feels. There’s a live demo.

Yousef

TresJS: Build 3D Experiences with Vue.js — Create 3D scenes with Vue components and Three.js. Think React-three-fiber but Vue flavored.

Alvaro Sabu

depngn: Find Out if Dependencies Support a Given Node.js Version — A CLI tool that establishes whether or not the dependencies in your package.json will work against a specified version of Node.

OmbuLabs

Open-Source JS Form Libraries to Automate Your Form Workflow — Self-host SurveyJS to configure and modify multiple forms, convert them to fillable PDF files, and analyze collected data in interactive dashboards.

SurveyJS sponsor

Lawnmower: Build VR Scenes with Custom HTML Tags — A web component library that leans on Three.js and aims “to make building a basic VR website as easy to make as your first HTML site”.

Gareth Marland

Electron 23.0 Released — The popular cross platform JavaScript, HTML + CSS desktop app framework gets bumped up to Node 18.12.1, Chromium 110, and V8 11.0. Windows 7/8/8.1 support has also been dropped, so we might start to see those versions of Windows lose the support of a lot of Electron based apps soon.

Electron Core Team

Run: Run User-Provided Code in a Web Worker

SLASHD Analytics

? Jobs

Software Engineer (Backend) — Join our “kick ass” team. Our software team operates from 17 countries and we’re always looking for more exceptional engineers.

Sticker Mule

Find JavaScript Jobs with Hired — Hired makes job hunting easy-instead of chasing recruiters, companies approach you with salary details up front. Create a free profile now.

Hired

QUICK RELEASES:

vue-easytable 2.23
↳ A data table/grid control for Vue.js. (Demo.)

React-Custom-Scroll 5.0
↳ Customize the browser scroll bar. (Demo.)

react-jsonschema-form 5.1
↳ Component to build Web forms from JSON Schema.

AlaSQL.js 3.1
↳ JavaScript-based SQL database.

jest-puppeteer 7.0
↳ Run tests using Jest & Puppeteer.

MDX 2.3
↳ Markdown for the component era.

? The Bonus Round

✈️ Watching someone wrestle with Python and JavaScript to fly (virtual) planes with Microsoft Flight Simulator tickled me a lot.

A beautiful WebGL2-based fluid simulation. It’s even happy on mobile. Pretty!

Go-like channels in 10 lines of JavaTypeScript..?

? Misko Hevery: “useSignal() is the future of web frameworks and is a better abstraction than useState(), which is showing its age.” (source)

Mike Pennisi asks: when is an object property not a property?

Do you use Postgres at all? Check out Postgres Weekly – one of our sister newsletters. So much is going on in the Postgres space lately and it’s a great way to keep up.

Flatlogic Admin Templates banner

Develop a serverless application in Python using Amazon CodeWhisperer

While writing code to develop applications, developers must keep up with multiple programming languages, frameworks, software libraries, and popular cloud services from providers such as AWS. Even though developers can find code snippets on developer communities, to either learn from them or repurpose the code, manually searching for the snippets with an exact or even similar use case is a distracting and time-consuming process. They have to do all of this while making sure that they’re following the correct programming syntax and best coding practices.

Amazon CodeWhisperer, a machine learning (ML) powered coding aide for developers, lets you overcome those challenges. Developers can simply write a comment that outlines a specific task in plain English, such as “upload a file to S3.” Based on this, CodeWhisperer automatically determines which cloud services and public libraries are best-suited for the specified task, it creates the specific code on the fly, and then it recommends the generated code snippets directly in the IDE. And this isn’t about copy-pasting code from the web, but generating code based on the context of your file, such as which libraries and versions you have, as well as the existing code. Moreover, CodeWhisperer seamlessly integrates with your Visual Studio Code and JetBrains IDEs so that you can stay focused and never leave the development environment. At the time of this writing, CodeWhisperer supports Java, Python, JavaScript, C#, and TypeScript.

In this post, we’ll build a full-fledged, event-driven, serverless application for image recognition. With the aid of CodeWhisperer, you’ll write your own code that runs on top of AWS Lambda to interact with Amazon Rekognition, Amazon DynamoDB, Amazon Simple Notification Service (Amazon SNS), Amazon Simple Queue Service (Amazon SQS), Amazon Simple Storage Service (Amazon S3), and third-party HTTP APIs to perform image recognition. The users of the application can interact with it by either sending the URL of an image for processing, or by listing the images and the objects present on each image.

Solution overview

To make our application easier to digest, we’ll split it into three segments:

Image download – The user provides an image URL to the first API. A Lambda function downloads the image from the URL and stores it on an S3 bucket. Amazon S3 automatically sends a notification to an Amazon SNS topic informing that a new image is ready for processing. Amazon SNS then delivers the message to an Amazon SQS queue.

Image recognition – A second Lambda function handles the orchestration and processing of the image. It receives the message from the Amazon SQS queue, sends the image for Amazon Rekognition to process, stores the recognition results on a DynamoDB table, and sends a message with those results as JSON to a second Amazon SNS topic used in section three. A user can list the images and the objects present on each image by calling a second API which queries the DynamoDB table.

3rd-party integration – The last Lambda function reads the message from the second Amazon SQS queue. At this point, the Lambda function must deliver that message to a fictitious external e-mail server HTTP API that supports only XML payloads. Because of that, the Lambda function converts the JSON message to XML. Lastly, the function sends the XML object via HTTP POST to the e-mail server.

The following diagram depicts the architecture of our application:

Figure 1. Architecture diagram depicting the application architecture. It contains the service icons with the component explained on the text above.

Prerequisites

Before getting started, you must have the following prerequisites:

An AWS account and an Administrator user

Install and authenticate the AWS CLI. You can authenticate with an AWS Identity and Access Management (IAM) user or an AWS Security Token Service (AWS STS) token.
Install Python 3.7 or later.
Install Node Package Manager (npm).

Install the AWS CDK Toolkit.
Install the AWS Toolkit for VS Code or for JetBrains.

Install Git.

Configure environment

We already created the scaffolding for the application that we’ll build, which you can find on this Git repository. This application is represented by a CDK app that describes the infrastructure according to the architecture diagram above. However, the actual business logic of the application isn’t provided. You’ll implement it using CodeWhisperer. This means that we already declared using AWS CDK components, such as the API Gateway endpoints, DynamoDB table, and topics and queues. If you’re new to AWS CDK, then we encourage you to go through the CDK workshop later on.

Deploying AWS CDK apps into an AWS environment (a combination of an AWS account and region) requires that you provision resources that the AWS CDK needs to perform the deployment. These resources include an Amazon S3 bucket for storing files and IAM roles that grant permissions needed to perform deployments. The process of provisioning these initial resources is called bootstrapping. The required resources are defined in an AWS CloudFormation stack, called the bootstrap stack, which is usually named CDKToolkit. Like any CloudFormation stack, it appears in the CloudFormation console once it has been deployed.

After cloning the repository, let’s deploy the application (still without the business logic, which we’ll implement later on using CodeWhisperer). For this post, we’ll implement the application in Python. Therefore, make sure that you’re under the python directory. Then, use the cdk bootstrap command to bootstrap an AWS environment for AWS CDK. Replace {AWS_ACCOUNT_ID} and {AWS_REGION} with corresponding values first:

cdk bootstrap aws://{AWS_ACCOUNT_ID}/{AWS_REGION}

For more information about bootstrapping, refer to the documentation.

The last step to prepare your environment is to enable CodeWhisperer on your IDE. See Setting up CodeWhisperer for VS Code or Setting up Amazon CodeWhisperer for JetBrains to learn how to do that, depending on which IDE you’re using.

Image download

Let’s get started by implementing the first Lambda function, which is responsible for downloading an image from the provided URL and storing that image in an S3 bucket. Open the get_save_image.py file from the python/api/runtime/ directory. This file contains an empty Lambda function handler and the needed inputs parameters to integrate this Lambda function.

url is the URL of the input image provided by the user,

name is the name of the image provided by the user, and

S3_BUCKET is the S3 bucket name defined by our application infrastructure.

Write a comment in natural language that describes the required functionality, for example:

# Function to get a file from url

To trigger CodeWhisperer, hit the Enter key after entering the comment and wait for a code suggestion. If you want to manually trigger CodeWhisperer, then you can hit Option + C on MacOS or Alt + C on Windows. You can browse through multiple suggestions (if available) with the arrow keys. Accept a code suggestion by pressing Tab. Discard a suggestion by pressing Esc or typing a character.

For more information on how to work with CodeWhisperer, see Working with CodeWhisperer in VS Code or Working with Amazon CodeWhisperer from JetBrains.

You should get a suggested implementation of a function that downloads a file using a specified URL. The following image shows an example of the code snippet that CodeWhisperer suggests:

Figure 2. Screenshot of the code generated by CodeWhisperer on VS Code. It has a function called get_file_from_url with the implementation suggestion to download a file using the requests lib.

Be aware that CodeWhisperer uses artificial intelligence (AI) to provide code recommendations, and that this is non-deterministic. The result you get in your IDE may be different from the one on the image above. If needed, fine-tune the code, as CodeWhisperer generates the core logic, but you might want to customize the details depending on your requirements.

Let’s try another action, this time to upload the image to an S3 bucket:

# Function to upload image to S3

As a result, CodeWhisperer generates a code snippet similar to the following one:

Figure 3. Screenshot of the code generated by CodeWhisperer on VS Code. It has a function called upload_image with the implementation suggestion to download a file using the requests lib and upload it to S3 using the S3 client.

Now that you have the functions with the functionalities to download an image from the web and upload it to an S3 bucket, you can wire up both functions in the Lambda handler function by calling each function with the correct inputs.

Image recognition

Now let’s implement the Lambda function responsible for sending the image to Amazon Rekognition for processing, storing the results in a DynamoDB table, and sending a message with those results as JSON to a second Amazon SNS topic. Open the image_recognition.py file from the python/recognition/runtime/ directory. This file contains an empty Lambda and the needed inputs parameters to integrate this Lambda function.

queue_url is the URL of the Amazon SQS queue to which this Lambda function is subscribed,

table_name is the name of the DynamoDB table, and

topic_arn is the ARN of the Amazon SNS topic to which this Lambda function is published.

Using CodeWhisperer, implement the business logic of the next Lambda function as you did in the previous section. For example, to detect the labels from an image using Amazon Rekognition, write the following comment:

# Detect labels from image with Rekognition

And as a result, CodeWhisperer should give you a code snippet similar to the one in the following image:

Figure 4. Screenshot of the code generated by CodeWhisperer on VS Code. It has a function called detect_labels with the implementation suggestion to use the Rekognition SDK to detect labels on the given image.

You can continue generating the other functions that you need to fully implement the business logic of your Lambda function. Here are some examples that you can use:

# Save labels to DynamoDB

# Publish item to SNS

# Delete message from SQS

Following the same approach, open the list_images.py file from the python/recognition/runtime/ directory to implement the logic to list all of the labels from the DynamoDB table. As you did previously, type a comment in plain English:

# Function to list all items from a DynamoDB table

Other frequently used code

Interacting with AWS isn’t the only way that you can leverage CodeWhisperer. You can use it to implement repetitive tasks, such as creating unit tests and converting message formats, or to implement algorithms like sorting and string matching and parsing. The last Lambda function that we’ll implement as part of this post is to convert a JSON payload received from Amazon SQS to XML. Then, we’ll POST this XML to an HTTP endpoint.

Open the send_email.py file from the python/integration/runtime/ directory. This file contains an empty Lambda function handler. An event is a JSON-formatted document that contains data for a Lambda function to process. Type a comment with your intent to get the code snippet:

# Transform json to xml

As CodeWhisperer uses the context of your files to generate code, depending on the imports that you have on your file, you’ll get an implementation such as the one in the following image:

Figure 5. Screenshot of the code generated by CodeWhisperer on VS Code. It has a function called json_to_xml with the implementation suggestion to transform JSON payload into XML payload.

Repeat the same process with a comment such as # Send XML string with HTTP POST to get the last function implementation. Note that the email server isn’t part of this implementation. You can mock it, or simply ignore this HTTP POST step. Lastly, wire up both functions in the Lambda handler function by calling each function with the correct inputs.

Deploy and test the application

To deploy the application, run the command cdk deploy –all. You should get a confirmation message, and after a few minutes your application will be up and running on your AWS account. As outputs, the APIStack and RekognitionStack will print the API Gateway endpoint URLs. It will look similar to this example:

Outputs:

APIStack.RESTAPIEndpoint01234567 = https://examp1eid0.execute-
api.{your-region}.amazonaws.com/prod/

The first endpoint expects two string parameters: url (the image file URL to download) and name (the target file name that will be stored on the S3 bucket). Use any image URL you like, but remember that you must encode an image URL before passing it as a query string parameter to escape the special characters. Use an online URL encoder of your choice for that. Then, use the curl command to invoke the API Gateway endpoint:

curl -X GET ‘https://examp1eid0.execute-api.eu-east-
2.amazonaws.com/prod?url={encoded-image-URL}&amp;name={file-name}’

Replace {encoded-image-URL} and {file-name} with the corresponding values. Also, make sure that you use the correct API endpoint that you’ve noted from the AWS CDK deploy command output as mentioned above.

It will take a few seconds for the processing to happen in the background. Once it’s ready, see what has been stored in the DynamoDB table by invoking the List Images API (make sure that you use the correct URL from the output of your deployed AWS CDK stack):

curl -X GET ‘https://examp1eid7.execute-api.eu-east-2.amazonaws.com/prod’

After you’re done, to avoid unexpected charges to your account, make sure that you clean up your AWS CDK stacks. Use the cdk destroy command to delete the stacks.

Conclusion

In this post, we’ve seen how to get a significant productivity boost with the help of ML. With that, as a developer, you can stay focused on your IDE and reduce the time that you spend searching online for code snippets that are relevant for your use case. Writing comments in natural language, you get context-based snippets to implement full-fledged applications. In addition, CodeWhisperer comes with a mechanism called reference tracker, which detects whether a code recommendation might be similar to particular CodeWhisperer training data. The reference tracker lets you easily find and review that reference code and see how it’s used in the context of another project. Lastly, CodeWhisperer provides the ability to run scans on your code (generated by CodeWhisperer as well as written by you) to detect security vulnerabilities.

During the preview period, CodeWhisperer is available to all developers across the world for free. Get started with the free preview on JetBrains, VS Code or AWS Cloud9.

About the author:

Rafael Ramos

Rafael is a Solutions Architect at AWS, where he helps ISVs on their journey to the cloud. He spent over 13 years working as a software developer, and is passionate about DevOps and serverless. Outside of work, he enjoys playing tabletop RPG, cooking and running marathons.

Caroline Gluck

Caroline is an AWS Cloud application architect based in New York City, where she helps customers design and build cloud native data science applications. Caroline is a builder at heart, with a passion for serverless architecture and machine learning. In her spare time, she enjoys traveling, cooking, and spending time with family and friends.

Jason Varghese

Jason is a Senior Solutions Architect at AWS guiding enterprise customers on their cloud migration and modernization journeys. He has served in multiple engineering leadership roles and has over 20 years of experience architecting, designing and building scalable software solutions. Jason holds a bachelor’s degree in computer engineering from the University of Oklahoma and an MBA from the University of Central Oklahoma.

Dmitry Balabanov

Dmitry is a Solutions Architect with AWS where he focuses on building reusable assets for customers across multiple industries. With over 15 years of experience in designing, building, and maintaining applications, he still loves learning new things. When not at work, he enjoys paragliding and mountain trekking.

Building .NET 7 Applications with AWS CodeBuild

AWS CodeBuild is a fully managed DevOps service for building and testing your applications. As a fully managed service, there is no infrastructure to manage and you pay only for the resources that you use when you are building your applications. CodeBuild provides a default build image that contains the current Long Term Support (LTS) version of the .NET SDK.

Microsoft released the latest version of .NET in November. This release, .NET 7, includes performance improvements and functionality, such as native ahead of time compilation. (Native AoT)..NET 7 is a Standard Term Support release of the .NET SDK. At this point CodeBuild’s default image does not support .NET 7. For customers that want to start using.NET 7 right away in their applications, CodeBuild provides two means of customizing your build environment so that you can take advantage of .NET 7.

The first option for customizing your build environment is to provide CodeBuild with a container image you create and maintain. With this method, customers can define the build environment exactly as they need by including any SDKs, runtimes, and tools in the container image. However, this approach requires customers to maintain the build environment themselves, including patching and updating the tools. This approach will not be covered in this blog post.

A second means of customizing your build environment is by using the install phase of the buildspec file. This method uses the default CodeBuild image, and adds additional functionality at the point that a build starts. This has the advantage that customers do not have the overhead of patching and maintaining the build image.

Complete documentation on the syntax of the buildspec file can be found here:

https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html

Your application’s buildspec.yml file contains all of the commands necessary to build your application and prepare it for deployment. For a typical .NET application, the buildspec file will look like this:

“`
version: 0.2
phases:
build:
commands:
– dotnet restore Net7TestApp.sln
– dotnet build Net7TestApp.sln
“`

Note: This build spec file contains only the commands to build the application, commands for packaging and storing build artifacts have been omitted for brevity.

In order to add the .NET 7 SDK to CodeBuild so that we can build your .NET 7 applications, we will leverage the install phase of the buildspec file. The install phase allows you to install any third-party libraries or SDKs prior to beginning your actual build.

“`
install:
commands:
– curl -sSL https://dot.net/v1/dotnet-install.sh | bash /dev/stdin –channel STS
“`

The above command downloads the Microsoft install script for .NET and uses that script to download and install the latest version of the .NET SDK, from the Standard Term Support channel. This script will download files and set environment variables within the containerized build environment. You can use this same command to automatically pull the latest Long Term Support version of the .NET SDK by changing the command argument STS to LTS.

Your updated buildspec file will look like this:

“`
version: 0.2
phases:
install:
commands:
– curl -sSL https://dot.net/v1/dotnet-install.sh | bash /dev/stdin –channel STS
build:
commands:
– dotnet restore Net7TestApp/Net7TestApp.sln
– dotnet build Net7TestApp/Net7TestApp.sln
“`

Once you check in your buildspec file, you can start a build via the CodeBuild console, and your .NET application will be built using the .NET 7 SDK.

As your build runs you will see output similar to this:

“`
Welcome to .NET 7.0!
———————
SDK Version: 7.0.100
Telemetry
———
The .NET tools collect usage data in order to help us improve your experience. It is collected by Microsoft and shared with the community. You can opt-out of telemetry by setting the DOTNET_CLI_TELEMETRY_OPTOUT environment variable to ‘1’ or ‘true’ using your favorite shell.

Read more about .NET CLI Tools telemetry: https://aka.ms/dotnet-cli-telemetry
—————-
Installed an ASP.NET Core HTTPS development certificate.
To trust the certificate run ‘dotnet dev-certs https –trust’ (Windows and macOS only).
Learn about HTTPS: https://aka.ms/dotnet-https
—————-
Write your first app: https://aka.ms/dotnet-hello-world
Find out what’s new: https://aka.ms/dotnet-whats-new
Explore documentation: https://aka.ms/dotnet-docs
Report issues and find source on GitHub: https://github.com/dotnet/core
Use ‘dotnet –help’ to see available commands or visit: https://aka.ms/dotnet-cli
————————————————————————————–
Determining projects to restore…
Restored /codebuild/output/src095190443/src/git-codecommit.us-east-2.amazonaws.com/v1/repos/net7test/Net7TestApp/Net7TestApp/Net7TestApp.csproj (in 586 ms).
[Container] 2022/11/18 14:55:08 Running command dotnet build Net7TestApp/Net7TestApp.sln
MSBuild version 17.4.0+18d5aef85 for .NET
Determining projects to restore…
All projects are up-to-date for restore.
Net7TestApp -> /codebuild/output/src095190443/src/git-codecommit.us-east-2.amazonaws.com/v1/repos/net7test/Net7TestApp/Net7TestApp/bin/Debug/net7.0/Net7TestApp.dll
Build succeeded.
0 Warning(s)
0 Error(s)
Time Elapsed 00:00:04.63
[Container] 2022/11/18 14:55:13 Phase complete: BUILD State: SUCCEEDED
[Container] 2022/11/18 14:55:13 Phase context status code: Message:
[Container] 2022/11/18 14:55:13 Entering phase POST_BUILD
[Container] 2022/11/18 14:55:13 Phase complete: POST_BUILD State: SUCCEEDED
[Container] 2022/11/18 14:55:13 Phase context status code: Message:
“`

Conclusion

Adding .NET 7 support to AWS CodeBuild is easily accomplished by adding a single line to your application’s buildspec.yml file, stored alongside your application source code. This change allows you to keep up to date with the latest versions of .NET while still taking advantage of the managed runtime provided by the CodeBuild service.

About the author:

Tom Moore

Tom Moore is a Sr. Specialist Solutions Architect at AWS, and specializes in helping customers migrate and modernize Microsoft .NET and Windows workloads into their AWS environment.

12+ Best Node.js Frameworks for Web App Development in 2022

Node.js is getting increasingly popular among developers, to the point where some developers call Node.js their primary choice for backend development. In this article, we review the 12 best Node.js web frameworks that we rate according to their popularity and unique toolkits for time and cost-efficiency.

Is Node.js a web framework?

So is Node.js a web framework? The most common way of referring to it is as a web framework. Still, Node.js is a JavaScript execution environment – a server-side platform for JavaScript code execution and portability. Instead, web frameworks focus on building features. A lot of developers have built Node.js web frameworks, such as Nest.js, Express.js, and other toolkits, for Node.js applications, providing a unique experience for software developers.

What are Node.js web frameworks?

Every web application technology offers different types of frameworks, all supporting a specific use case in the development lifecycle. Node.js web frameworks come in three types – Full-Stack Model-View-Controller (MVC), MVC, and REST API web frameworks.

Node.js web framework features

API of Node.js is asynchronous. You can use the Node.js server to move after a data request, rather than waiting for the API to return the information.
The code execution process of Node.js is faster compared to the reverse backend framework.
Node.js runs on a single-threaded model.
With Node.js web framework developers never face buffering issues because it transfers information by parts.
It is supported by Google’s Node.js runtime environment.

Through these features, it is clear to understand why developers more often choose Node.js for Backend development. Let’s take a closer look at each Node.js web framework.

NestJS

Github repo: https://github.com/nestjs/nest
License: MIT
Github stars: 47400

NestJS is object-oriented and functional-reactive programming (FRP), widely used for developing enterprise-level dynamic and scalable web solutions, being well featured with extensive libraries.

NestJS is based on TypeScript as its core programming language, but is also highly compatible with a JavaScript subset and easily integrated with other frameworks such as ExpressJS through a command-line interface.

Why use NestJS:

Modern CLI
 functional-reactive programming
Multiple easy-to-use external libraries
Straightforward Angular compatibility

NestJS has a clean and modular architecture pattern aiding developers to build scalable and maintainable applications with ease. 

Pros of NestJS:

Powerful but super friendly to work with
Fast development
Easy to understand documentation
Angular style syntax for the backend

NodeJS ecosystem
Typescript
Its easy to understand since it follows angular syntax
Good architecture
Integrates with Narwhal Extensions
Typescript makes it well integrated in vscode
Graphql support easy
Agnosticism
Easily integrate with others external extensions

ExpressJS

Github repo: https://github.com/expressjs/express
License: MIT
Github stars: 57200

ExpressJS is minimalistic, asynchronous, fast, and powerful and was launched in 2010. It’s beginner-friendly thanks to a low learning curve that requires only a basic understanding of the Node.js environment and programming skills. ExpressJS optimises client-to-server requests and observed user interaction via an API very quickly, and also helps you manage high-speed I/O operations. 

Why use ExpressJS:

Enhanced content coordination
MVC architecture pattern
HTTP helpers
Asynchronous programming to support multiple independent operations

ExpressJS offers templating, robust routing, security and error handling, making it suitable for building enterprise or browser-based applications.

Pros of ExpressJS :

Simple
NodeJS
Javascript
High performance
Robust routing
Middlewares
Open source
Great community
Hybrid web applications
Well documented
Light weight

Meteor

Github repo: https://github.com/meteor/meteor
License: MIT
Github stars: 42900

Meteor is an open-source framework that was launched in 2012 that works best for teams who want to develop in a single language, being a full-featured Node.js web framework. Meteor is ideal for modern real-time applications as it facilitates instant data transfer between server and client.

Why use Meteor:

Cross-platform web framework
Rapid prototyping using the CLI
Extensive community support and open-source code
End-to-end solution
Seamless integration with other frameworks

The Meteor is an excellent option for those who are familiar with Javascript and prefer it. It’s a great one for both web and mobile app development as well. Meteor is great for applications that require a lot of updates that need to be sent out, even in a live environment.

Pros of Meteor :

Real-time
Full stack, one language
Best app dev platform available today
Data synchronization
Javascript
Focus on your product not the plumbing
Hot code pushes
Open source
Live page updates
Latency compensation
Ultra-simple development environment
Great for beginners
Smart Packages

KoaJS

Github repo: https://github.com/koajs/koa
License: MIT
Github stars: 32700

Koa has been called the next-generation Node.js web framework, and it’s one of the best of the bunch. Koa uses a stack-based approach to handling HTTP mediators, which makes it a great option for easy API development. Koa is similar to ExpressJS, so it’s fairly easy to switch from either one. Despite the same features and flexibility, Koa reduces the complexity of writing code even more.  

Why use Koa:

Multi-level customisation
Considered a lightweight version of ExpressJS
Supplied with cascading middleware ( user experience personalisation)
Node mismatch normalization
Cleans caches and supports content and proxy negotiation

Use Koa when performance is the main focus of your web application. Koa is ahead of ExpressJS in some scenarios, so you can use it for large-scale projects. 

Pros of Koa :

Async/Await
JavaScript
REST API

socket.io

Github repo:https://github.com/socketio/socket.io
License: MIT
Github stars: 55900

The socket is a Javascript library that works most effectively for real-time web applications. The socket is used when communication between real-time web clients and servers needs to be efficiently bidirectional. 

Why use socket.io:

Binary support
Multiplexing support
Reliability
Auto-reconnection support
Auto-correction and error detection 

The socket is a great choice when building real-time applications like video conferencing, chat rooms and multiplayer games with servers being required to send data out before it’s requested from the client-side.

Pros of socket :

Real-time
Event-based communication
NodeJS
WebSockets
Open source
Binary streaming
No internet dependency
Large community

TotalJS

Github repo: https://github.com/totaljs/
License: MIT
Github stars: n/a

TotalJS is a web framework that offers a CMS-like user experience and has almost all the functionality you need in a Node.js environment. The framework is a full open-source framework that provides developers with the ultimate flexibility. There are various options available for the framework, e.g. CMS, and HelpDesk. Through these options, your application will have more integration possibilities with the REST service and hyper-fast, low-maintenance, stable applications. 

TotalJS is most well-known for its real-time, high-precision tracking in modern applications. 

Pros of TotalJS:

Tracking in real-time
API Testing
Automatic project discovery
Compatibility with multiple databases
Flexibility to work with different frontend frameworks
Fast development and low cost of maintenance

SailsJS

Github repo: https://github.com/balderdashy/sails
License: MIT
Github stars: 22247

SailsJS is similar to the MVC architect pattern of web frameworks such as Ruby on Rails, and it supports modernized data-centric development. Compatible with all databases, at the same time it flexibly integrates Javascript frameworks. SailsJS is the most relevant framework for building high-quality custom applications. Its special code-writing policy helps reduce the code needed, allowing you to integrate npm modules while remaining flexible and open source. 

Pros of SailsJS:

REST API auto-generation
Multiple security policies
Frontend agnosticism
Object Relational Mapping for framework databases compatibility
Supports ExpressJS integration for HTTP requests and socket.io for WebSockets 

FeathersJS

Github repo: https://github.com/feathersjs/feathers
License: MIT
Github stars: 14000

FeathersJS is gaining popularity between website and application developers because it provides flexibility in development with react native as well as Node.js. It is a framework of microservices because it operates with more than one database, providing real-time functionality. FeathersJS makes it easier for web developers to code concretely and understandably.

Pros of FeathersJS:

Reusable services
Modern CLI
Automated RESTful APIs
Authentication and authorization plugins by default
Lightweight

FeathersJS natively supports all frontend technologies, and its database-agnostic is best performed in a Node.js environment because the web framework supports Javascript and Typescript. It allows you to create production-ready applications and real-time applications, and also REST APIs in just a few days.

hapi.dev

Github repo: https://github.com/hapijs/hapi
License: MIT
Github stars: 13900

Hapi is an open-source framework for web applications. It is well-known for proxy server development as well as REST APIs and some other desktop applications since the framework is robust and security-rich. It has a wealth of built-in plugins, therefore this means you don’t have to worry about running non-official middleware. 

Pros of Hapi:

Extensive and scalable applications
Low overhead
Secure default settings
Rich ecosystem
Quick and easy bug fixes
Compatible with multiple databases
Compatible with Rest API and HTTPS proxy applications
Caching, authentication and input validation by default

AdonisJS

Github repo: https://github.com/adonisjs/core
License: MIT
Github stars: 12600

AdonisJS is a Model-View-Controller Node.js web framework based on a structural template repeating Laravel. The framework decreases the time required for development by focusing on core details such as out of the box web socket support, development speed and performance, lifecycle dependency management, and built-in modules for data validation, mailing, and authentication. Command-based coding structure and the interface is easy for developers to understand. The Node.js web framework uses the concepts of dependency injections through IoC or control inversion. It offers developers an organized structure for accessing all the components of the framework. 

Pros of AdonisJS:

Organised template with folder structure
Easy user input validation.
Ability to write custom functional testing scripts
Support for Lucid object-relational mapping.
Threat protection such as cross-site forgery protection

Loopback

Github repo: https://github.com/loopbackio/loopback-next
License: MIT
Github stars: 4200

Loopback provides the best connection with any Node.js web framework and can be integrated with multiple API services. You can best use the platform to build REST APIs with minimal lead time. Loopback offers outstanding flexibility, interfacing with a broad range of browsers, devices,  databases, and services. Framework’s structured code helps support application modules and speed of development. Loopback has the best documentation, allowing even beginners to work with it. 

Pros of Loopback:

Comprehensive support for networked applications
The built-in client API explorer
High extensibility
Multiple database support
Clean and modular code
Full-stack development
Data storage, third-party access, and user management

Loopback is designed solely for creating powerful end-to-end APIs and handling requests for them. 

DerbyJS

Github repo: https://github.com/derbyjs/derby
License: MIT
Github stars: 4622

DerbyJS is a full-stack web application development platform powered by Node.js technology. This framework uses the Model-View-Controller architecture with an easy-to-write nomenclature for coding. This framework is great for building real-time web applications since it allows essentially the same code to work on Node.js and in the browser. That way, you don’t have to worry about writing separate codes for the view part. DerbyJS decreases the delay in content delivery by rendering a client-side view on the server. Performing this makes the application SEO-friendly and improves the user experience. 

Pros of DerbyJS:

Support for Racer Engine
Real-time conversion for data synchronization
Offline use and conflict resolution support

Version control
Client-side and server-side code sharing
Rendering client-side views on the server-side

Conclusion

Node.js web frameworks make application development easier with their enormous possibilities for the advancement of web and mobile application development.  Under the conditions of increasingly growing technologies, a thorough investigation of project requirements and accessibility of resources is the key to choosing the right web framework that will provide the greatest results.

The post 12+ Best Node.js Frameworks for Web App Development in 2022 appeared first on Flatlogic Blog.Flatlogic Admin Templates banner

Build Your Own Little Menu Bar App for All Those Things you Forget

I have a little Pinned Pen of Things I Forget that I revisit quite a bit… when… I forget… things. It occurred to me the other day that it would be even more convenient as a menu bar app (macOS) than a Pen. Maybe an excuse to learn Swift? Nahhh. There’s always an app for that. I know Fluid can do that, but I wasn’t 100% sure if that’s up to date anymore or what. As I happen to be a Setapp subscriber, I know they have Unite as well, which is very similar.

So let’s do this! (This is a macOS thing, for the record.)

1) Make a little website of Things You Forget that allows you to one-click copy to clipboard.

You don’t need a special URL or anything for it. And good news, CodePen Projects can deploy your Project to a URL with a click.

Here’s my example Project.

2) Deploy it

Now I click that Deploy button in the footer and can kick it out to a live-on-the-internet URL easily.

3) Turn it into a Menu Bar App with Unite

Then I launch Unite and give it the barebones information it needs:

That’ll instantly make the app. It takes like 2 seconds. From here, two things:

Paste a better image into the Get Info window so you can have a cool icon.
If you’re on an M1 Mac, you might have to click the “Open using Rosetta” icon in order for it to work.

That second one is a little unfortunate. Makes me wish I tried Fluid, but hey, this ultimately worked. You’ll know you need to do it if you see this:

4) Enjoy

A totally custom-designed app to help your own brain!

The post Build Your Own Little Menu Bar App for All Those Things you Forget appeared first on CodePen Blog.Flatlogic Admin Templates banner

Adding feature flags to an ASP.NET Core app

This post is about Adding feature flags to an ASP.NET Core app.Feature flags (also known as feature toggles or feature switches) are a software development technique that turns certain functionality on and off during runtime, without deploying new code. In this post we will discuss about flags using appsettings.json file. I am using an ASP.NET Core MVC project, you can do it for any .NET Core project like Razor Web Apps, or Web APIs.

First we need to add reference of Microsoft.FeatureManagement.AspNetCore nuget package – This package created by Microsoft, it will support creation of simple on/off feature flags as well as complex conditional flags. Once this package added, we need to add the following code to inject the Feature Manager instance to the http pipeline.

using Microsoft.FeatureManagement;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();

builder.Services.AddFeatureManagement();

var app = builder.Build();

Next we need to create a FeatureManagement section in the appsettings.json with feature with a boolean value like this.

“FeatureManagement”: {
“WelcomeMessage”: false
}

Now we are ready with feature toggle, let us write code to manage it from the controller. In the controller, ASP.NET Core runtime will inject an instance of the IFeatureManager. And in this interface we can check whether a feature is enabled or not using the IsEnabledAsync method. So for our feature we can do it like this.

public async Task<IActionResult> IndexAsync()
{
if(await _featureManager.IsEnabledAsync(“WelcomeMessage”))
{
ViewData[“WelcomeMessage”] = “Welcome to the Feature Demo app.”;
}
return View();
}

And in the View we can write the following code.

@if (ViewData[“WelcomeMessage”] != null)
{
<div class=“alert alert-primary” role=“alert”>
@ViewData[“WelcomeMessage”]
</div>
}

Run the application, the alert will not be displayed. You can change the WelcomeMessage to true and refresh the page – it will display the bootstrap alert.

This way you can start introducing Feature Flags or Feature Toggles in ASP.NET Core MVC app. As you may already noticed the Feature Management library built on top of the configuration system of .NET Core. So it will support any configuration sources as Feature flags source. Microsoft Azure provides Azure App Configuration service which helps to implement feature flags for cloud native apps.

Happy Programming 🙂Flatlogic Admin Templates banner

Laravel Validation Guide: Methods, Rules & Custom Messages

Introduction
Amazing Laravel

Installation of Laravel
Laravel Installation via Composer
Laravel Installation via Flatlogic Platform

Creating a View to work on Laravel Validation
4 Great Methods of Laravel Validation
Laravel Validation Using Flatlogic platform
How to create Custom Rule Classes
Custom Laravel Validation messages
Most popular validation Rules in Laravel
Conclusion

Introduction

Does your Laravel project need validation? You do not know how to implement validation, or look for best practices, right? You have come to the right address. Working with projects on Laravel (including code reviews), I came across different ways to implement validation. As I have seen, validation can be implemented by various methods which are not always correct in terms of SOLID principles and best practices. As a result, projects in which the validation logic is implemented incorrectly become even more problematic over time. The code is confusing, turning out to be a salad of different unrelated processes. In this article, we will explore the various ways of validating in Laravel. Including frankly bad ones.

Amazing Laravel

I have to praise Laravel because I really love this framework. It is quite simple to learn and at the same time offers almost limitless possibilities. Laravel is a really wonderful MVC open-source PHP framework based on Symfony, developed over 10 years ago (July 2011) by Taylor Otwell. Laravel has found love and fame among web developers. Laravel has a huge community: meet Laracast and Laravel Forums. This month, on February 9, 2022, the next online Laracon began, the largest developer conference on Laravel.

Many popular websites have been written with Laravel. Among them are the large eLearning platform Alison.com (more than 4,000,000 monthly visitors according to similarweb), the leading portal for financial experts https://www.barchart.com, and also Laravel MVC framework is used by fedex.com, weibo.com (?), podium.com, and many others platforms (according to buildwith.com data).

Among other things, it is worth noting that Laravel takes 1st place in the Github Top PHP ranking, and Laravel based October CMS (Content Management System, written with Laravel) is the second-most-starred PHP CMS repository hosted on GitHub (July 2021 data).

So, we have already begun to study Laravel and how it works in the previous article What is Laravel, and today in this Guide we will study How Laravel Validation works. We will learn 4 different and excellent ways of Validation in Laravel. You can use each of these Laravel Validation methods in your projects. As mentioned earlier, some of these methods are not the best practices, however, I believe that you should be aware of them to use them at your discretion.

How Laravel Validation works

Firstly, we will learn Laravel Validation In Route (I know, this is the worst solution, but I think you need to know that it exists.)
Secondly, we will learn the “Classic” method: Immediate Laravel Validation in the Controller
Thirdly, we will learn the best practice method: Laravel Validation with Form Requests
Fourthly,  we will learn the geek method: Custom Laravel Validation using Laravel Validator

After that, we’ll talk about Custom Rule Classes, about Custom Laravel Validation Messages, and at the end of the article, we’ll look at the most popular ready-to-use rules that you can use for validation of your Laravel projects. 

Also in this article, you will learn how to save up to  $20,000 using a ready-made solution from Flatlogic Platform: in a few clicks, we will deploy a Laravel Project with a Vue front-end  (Angular and React front-ends are also available).

If you want even more features, then at the end of the article I will present a promo code for a Flatlogic Platform subscription, where you can test the incredible features of the platform. In a few clicks, you can not only create Laravel backend & Frontend (Vue, Angular, React) but also get a ready-made admin panel (various design options are available), a database and hosting.

So, enjoy reading. Let’s go.

Installation of Laravel

// You can skip this paragraph if your Laravel project is already installed

There are many awesome ways to install your Laravel project, but we will focus on two of my favorites that work flawlessly.

Laravel installation via Composer
Laravel installation via Flatlogic Platform

Laravel Installation via Composer

The most popular and rock star way to set up your Laravel project. Just open the folder where you are going to work, start a new terminal and ask Composer to do the magic

(I chose the name for my project “laravel-validation”, but you can use whatever name you want)

So, let’s dive into the project:

And ask Artizan to start the Development Server:

Voila, Artizan thought a little and complied with the request. Fantastic!

ATTENTION: The development server is running on port 8000. Bear this in mind when you open your project in a browser on your local machine.

So, open localhost:8000 and see a working project with the default page: 

Laravel Installation via Flatlogic Platform

Same easy to install Laravel, using the Flatlogic Platform. But in this case, we will get more ready-to-use solutions. Soon you will be able to verify this. Complete a simple registration here https://flatlogic.com/users/sign_in  and then go to the Admin Panel in your account and click Add Application

Next, come up with a name for your project (I chose Laravel Validation) and select the stack you want to work on. Click NEXT

Choose a ready-to-use Admin theme for your future admin panel. I really like Dark Mode, so I chose a dark admin template.

Next, select a ready-to-use Database Schema or invent your own. I chose the ready-to-use Blog schema. Dependencies are already established in this scheme and data types are registered.

It remains to give permission to access your GitHub repository for Flatlogic Bot and click Finish.

Here is the project:

The method described above differs from installing a Laravel project through Composer in that you get a ready-made admin panel, a database, and relationships between database entities.

Save the project to the local computer:

git clone {your github project path}

Install the backend:

composer install

ATTENTION: Your local machine may not match the PHP version. I needed to update my PHP version as the project uses version 7.4

Generating keys:

Install Vue js frontend

So, Laravel Project with Vue frontend has been set up. Later in this article, we will look at how to do Validation in this project. For now, let’s learn the basics. Move on forward.

Creating a View to work on Laravel Validation

Get started with the project which we’ve already created with Composer. Proceed with editing the View file. Open the project in your IDE (I use Visual Studio Code) and find the following file:

In order not to reinvent the wheel, we will use the Bootstrap 5 Library. Go to the following link https://getbootstrap.com/docs/5.1/forms/overview/  Copy the form code, remove everything unnecessary and place it in the file welcome.blade.php 

I got this one:

ATTENTION: Notice that I’ve added @csrf inside the form. This is an important thing in Laravel framework security issues, and we will talk about this separately in future articles. In the current case, remember that this is a security token and without it, Laravel will return a 419 server response.

So let’s restart our Development Server and check that everything works.

php artisan serve

Hint: If you need to stop the Development server in Laravel, press “Control+C”

So, we have done the initial setup: we have the Laravel project installed, we have View and now we can move on to learning 4 Great Methods of Laravel Validation.

4 Great Methods of Laravel Validation

Method #1: Easiest Laravel Validation in Route (God bless)

This method cannot be classed as a great method. In fact, I wanna say that it’s the worst method in the Universe. You shouldn’t use it unless you have no time at all because you are trying to hack NASA. However, I will tell you about it for the simple reason that you must understand how Laravel Validation works from Start to Finish.

Let’s create a route that returns our View(welcome.blade.php) with a form. Open routes/web.php and write a new route:

Route::get(‘/’, function(){return view(‘welcome’);});

Moving on forward. If you look in the application controller base class AppHttpControllersController, you will see that it uses the ValidatesRequests (IlluminateFoundationValidationValidatesRequests). This trait provides a convenient validate() method for all controllers.

So let’s add this controller to our routes/web.php routing file:

use AppHttpControllersValidationController;

And create a route, inside which be used a function with the validation of our form. It all looks like this:

The validate() method already contains the ready-to-use logic for validation, so we only need to enumerate the values. At the end of this article, we will study in more detail the values that this method offers for validation.

Well, let’s open localhost:8000 in the browser, fill in the fields with data, and click Submit. On the new page, we will see the result of the work.

Ready!

Before moving on to the next chapter, let’s catch errors. It’s very simple. It is enough to enter the {{$errors}} command on the welcome.blade.php page and they will be displayed on the page. Shall we try? It works, but it doesn’t look very good… Does it? Let’s add some logic so that errors are displayed beautifully:

Looks good!

ATTENTION: The $errors variable can be used thanks to the Middleware IlluminateViewMiddlewareShareErrorsFromSession. If you use this Middleware, the $errors variable will always be available in your templates. This $errors Variable will be an instance of IlluminateSupportMessageBag.

Method #2: Popular but Flawed; Immediately Laravel Validation in Controller

This method is also not ideal for use, as it violates the SOLID Single Responsibility Principle (SRP). However, I have seen many great Laravel projects that implement validation in this way.

So, let’s create a controller for validation. To do this, enter the following in the terminal command line:

php artisan make:controller ValidationController

I decided to give a name to my controller ValidationController, – you can give it any name you want, as long as the second word in the name is controller.

Next, open up our controller and create a simple function to display our View(welcome.blade.php)

Also, move validation logic from the routes/web.php routes to this controller

This is how a working ValidationController looks:

What happens in this function?

We get data from $request
We put data in the validate() function and perform validation
And finally, we store the result in $result. Awesome!

Now let’s fix the routes in our routes/web.php file

As you can see, now all the validation processing logic has moved from Routes(web.php) to the Controller.

Check how errors are handled:

And how the controller works if there are no errors:

Fantastic, isn’t it? Move on!

Method 3: Oskar Winner; Magic Laravel Validation with Form Requests

Continue to develop the validation logic. Now we need a Request. Let’s create new Request using Artisan:

php artisan make:request UserValidationRequest

As you can see I named my Request UserValidationrequest. Let’s investigate what lies inside it (you can find it in the project in the file App/Http/Requests/UserValidationRequest.php):

There are already 2 ready-to-use functions here: rules() and authorize().

Let’s immediately fix the authorize() function so as not to get a 403 server response (we have a different task now and we will not check authorization).

Now, let’s transfer the validation logic from our ValidationController controller to the rules() function that is in the newly created UserValidationRequest. This is how our UserValidationRequest now looks like:

Now the final steps. Let’s go to ValidationController and add the Request we just created:

That’s all. Now we will validate data using our newly created Request. To do this, it remains to fix the userValidation () function in the controller:

As you can see now, the new request with data first goes to the UserValidationRequest, and only after validation does it get to the Controller. This is a wonderful and accurate way of Validation in Laravel from all sides. And I recommend using it. Even in extreme situations;).

Method #4: Deep Divers and Geeks; Custom Laravel Validation using Laravel Validator

This method can be useful if it is important for your project to handle custom errors. The method makes extensive use of the Laravel Validator facade.

Let’s add it to our controller:

And now let’s make changes to our ValidationController controller:

While this method favors Custom Laravel Validation, I also oppose this method as it goes against the principles of SOLID. And if you don’t want to upset Mr. Robert C. Martin, then don’t use it. Think of how you can change this code so as not to violate the principles of SOLID

Laravel Validation using Flatlogic platform: Form Request 

We have already installed our Laravel Project with Vue frontend locally.

Let’s start the backend server

Attention: Pay attention to the port. By default, Laravel has a port number of 8000. The project uses port 8080.

Now let’s Run frontend development server:

Let’s open it in a browser and visually check the operation of the front-end server on port 3000:

And the backend server on port 8080:

Everything works great! Super!

Earlier in this article, we already learned how to make a Form Request. Let’s put our knowledge into practice. Let’s go to the backend folder and create a new Request for our project:

Familiar? Then we open the UserValidationRequest and make minor changes to it.

As you can see, I left only 2 fields for validation here, since in our front-end example there is a ready-to-use form in which only email and password need to be validated.

Next, open our controllers and look for AuthController there (let me remind you that the controllers are in the path backend/app/Http/Controllers/Api).

Let’s add our request to the __construct function:

And in namespaces:

And let’s see how everything works (I commented out all the logic and returned only what our UserValidationRequest returns. As you can see, I returned errors)

By default, the frontend logic already checks if the email is valid, so I only checked the length of the password and entered a password with 3 characters.

Laravel Validation: How to Create Custom Rule Classes  

https://laravel-news.com/laravel-validation-101-controllers-form-requests-and-rules

Let’s dive even deeper and see how to create Custom Rule Classes in Laravel Validation.

Create a rule:

Let’s open the project and look at the newly created rule. It is located at /app/Rules/IsValidSantasReindeer.php

Creating a validation function:

And add a custom message to visually verify that our code work properly:

Now let’s make changes in the app/Http/Requests/UserValidationRequest.php file:

We will check username with new rules. Let’s create an object:

new 

At the same time, app/Http/Controllers/ValidationController.php looks the same as in the Form Request chapter of this article.

Checking  how the new rule works. Let’s enter the wrong username in the “username” field:

Now we will enter one of the saved names and make sure that the error message is gone:

Fabulous!

Custom Laravel Validation messages

Let’s continue our dive and see how we can create Custom Laravel Validation Messages for our project. It’s actually very simple and I’ll show you how to do it through the previously studied Form Request.

In fact, it is enough to open the Request we created and add the messages () function:

As you can see, I changed the Required properties for the ‘username’, ‘age’, ’email’, ‘password’ entities. In exactly the same way, you can write your Custom messages for other properties. Let’s check if everything works correctly:

Yes! Everything is fine! Great!

Most Popular validation Rules in Laravel

To conclude our guide, let’s take a quick look at the most popular Validation Rules in Laravel.

#accepted

This rule returns true if the values are “yes”, “on”, 1, or true

I recommend using it when you check if the user has agreed to the terms of use, or when the user confirms whether he is 18 years old.

#after:date

A great rule of thumb if your user has to choose a time for a consultation. In this way, you will check that the user has not booked time for yesterday. Great rule. Here is an example of its use:

‘consultation_date’ => ‘required|date|after:tomorrow’

#bail

A great way not to load your server. Abort further validation checks if at least one property fails validation.

#before:date

This rule is great to check if the user was born later than today (unless you are creating a resource for time travelers).

#between:min.max

You can check if the user is trying to withdraw from the account more money than he has and less than the minimum amount that can be withdrawn

#confirmed

Used when you need to confirm a password

#digits:value

numerics are available for validation.

#integer

A very common rule when working with eCommerce. Check if the input is an integer.

#email

The most used rule. Here, as it is not difficult to guess, it is checked whether the user has entered an email.

#file

Checking if a file is loaded

#image

It’s also a fairly common rule. Checks if the file is an image. The following formats are supported: (jpg, jpeg, png, bmp, gif, svg, or webp).

#ip | #ipv4 | ipv6

Whether the data is ip, ipv4, or ipv6 format is checked accordingly.

#min:value | #max:value

These rules will prevent the novel by Keith C.Paine “Wow” and the novel by Marcel Proust “Remembrance of Things Past”  from appearing in your database.

#password

Password;)

#required

One of the most common rules. It will check, among other things, that there is no empty String, uploaded file with no path, or empty array.

You can learn more about validation rules here.

Conclusion

Today we have learned some great ways for Data Validation in Laravel MVC framework. We have learned Laravel Validation In Route, Laravel Validation in the Controller, Validation with Form Requests, and Custom Laravel Validation using Laravel Validator. We talk about Custom Rule Classes, Custom Laravel Validation Messages, and ready-to-use Rules that you can use for validation of your Laravel projects.

In addition, you have learned how easy it is to start a Laravel Project with Vue frontend and ready-to-use Admin dashboard for FREE using Flatlogic Platform. By deploying a project using the Flatlogic Platform, you initially save about 500 hours of development (time of the designer, frontend, and backend engineers) or $20,000. 

Use the promotional code VALIDATION50 and get a 50% discount for 1 month of the subscription. It has never been so easy to add a database and hosting to your project! Incredible! And it’s just a few clicks away!

We wish you good luck in developing your Laravel projects, and in order not to miss the news from us, subscribe to our YouTube channel and our email newsletter. We add to the mailing list not only news about Flatlogic Platform and educational articles but also new coupons and discounts for our products.

Cheers!

Suggested Articles

What is Laravel?
Sing App Vue Laravel Template is Released

The post Laravel Validation Guide: Methods, Rules & Custom Messages appeared first on Flatlogic Blog.Flatlogic Admin Templates banner