Skip to content

๐Ÿ”Š Echo

In this tutorial, weโ€™re going to build an app that exposes a single endpoint and responds with a dynamic response which echoes the path back.

When weโ€™re done, we should be able to make a GET request to the /<message> endpoint with any message:

Terminal window
# <message> is "ping"
curl --request GET \
--url http://localhost:8080/ping
# <message> is "pong"
curl --request GET \
--url http://localhost:8080/pong

And our server should respond with the following responses:

HTTP/1.1 200 OK
Connection: close
Content-Length: 21
Content-Type: text/plain; charset=utf-8
ping
---
HTTP/1.1 200 OK
Connection: close
Content-Length: 21
Content-Type: text/plain; charset=utf-8
pong

To create a new Dart Frog app, open your terminal, cd into the directory where youโ€™d like to create the app, and run the following command:

Terminal window
dart_frog create echo

You should see an output similar to:

โœ“ Creating echo (0.1s)
โœ“ Installing dependencies (1.7s)
Created echo at ./echo.
Get started by typing:
cd ./echo
dart_frog dev

You should now have a directory called echo โ€” cd into it:

Terminal window
cd echo

Then, run the following command:

Terminal window
dart_frog dev

This will start the development server on port 8080:

โœ“ Running on http://localhost:8080 (1.3s)
The Dart VM service is listening on http://127.0.0.1:8181/YKEF_nbwOpM=/
The Dart DevTools debugger and profiler is available at: http://127.0.0.1:8181/YKEF_nbwOpM=/devtools/#/?uri=ws%3A%2F%2F127.0.0.1%3A8181%2FYKEF_nbwOpM%3D%2Fws
[hotreload] Hot reload is enabled.

Make sure itโ€™s working by opening http://localhost:8080 in your browser or via cURL:

Terminal window
curl --request GET \
--url http://localhost:8080

If everything succeeded, you should see Welcome to Dart Frog!.

Now that we have a running application, letโ€™s start by deleting the root route since we wonโ€™t need it for this example:

Terminal window
rm routes/index.dart

Next, letโ€™s create routes/[message].dart:

Terminal window
touch routes/[message].dart

Finally, letโ€™s define an onRequest method in the newly created route:

import 'package:dart_frog/dart_frog.dart';
Response onRequest(RequestContext context, String message) {
return Response(body: message);
}

Save the changes and hot reload should kick in โšก๏ธ

Terminal window
[hotreload] - Application reloaded.

Make sure itโ€™s working by opening http://localhost:8080/ping in your browser or via cURL:

Terminal window
curl --request GET \
--url http://localhost:8080/ping

If everything succeeded, you should see your message echoed back โ€” in this case, we should see ping.

Letโ€™s try making a different request by visiting http://localhost:8080/pong in your browser or via cURL:

Terminal window
curl --request GET \
--url http://localhost:8080/pong

This time you should see pong.

๐ŸŽ‰ Congrats, youโ€™ve created an echo application using Dart Frog. View the full source code.