๐ 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:
# <message> is "ping"curl --request GET \ --url http://localhost:8080/ping
# <message> is "pong"curl --request GET \ --url http://localhost:8080/pongAnd our server should respond with the following responses:
HTTP/1.1 200 OKConnection: closeContent-Length: 21Content-Type: text/plain; charset=utf-8
ping
---
HTTP/1.1 200 OKConnection: closeContent-Length: 21Content-Type: text/plain; charset=utf-8
pongCreating a new app
Section titled โCreating a new appโ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:
dart_frog create echoYou should see an output similar to:
โ Creating echo (0.1s)โ Installing dependencies (1.7s)
Created echo at ./echo.
Get started by typing:
cd ./echodart_frog devRunning the development server
Section titled โRunning the development serverโYou should now have a directory called echo โ cd into it:
cd echoThen, run the following command:
dart_frog devThis 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:
curl --request GET \ --url http://localhost:8080If everything succeeded, you should see Welcome to Dart Frog!.
Creating a dynamic route
Section titled โCreating a dynamic routeโNow that we have a running application, letโs start by deleting the root route since we wonโt need it for this example:
rm routes/index.dartNext, letโs create routes/[message].dart:
touch routes/[message].dartFinally, 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 โก๏ธ
[hotreload] - Application reloaded.Make sure itโs working by opening
http://localhost:8080/ping in your browser or via
cURL:
curl --request GET \ --url http://localhost:8080/pingIf 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:
curl --request GET \ --url http://localhost:8080/pongThis time you should see pong.
๐ Congrats, youโve created an echo application using Dart Frog. View the
full source code.