Learn full-stack web development using fastn in a week
Learn Now
Fullstack
->
Getting Request Data

Getting Request Data

request-data processor can be used to find the data from the HTTP request. Query string and named-path parameters or from request body.
⚠️
Static Vs Dynamic
This feature works better with dynamic hosting. If you are using fastn in static site mode, then how the page looked when fastn build was called will be shown to everyone. But if you are using dynamic mode then this page would be regenerated on every page load.

Reading Individual Fields

Say the request was:
curl 'http://127.0.0.1:8000/test/?message=hello%20world'
Lang:
sh
And you wanted to extract the value of message, you can do it like this:
-- import: fastn/processors as pr

-- string message:
$processor$: pr.request-data    

-- ds.markdown: $message
Lang:
ftd
Note that the field must be present or else this will give an error.

Using Default Value As Fallback

If you expect the message to be optional, maybe the user made a request like this:
curl 'http://127.0.0.1:8000/test/'
Lang:
sh
without passing message, the earlier code will return HTTP 500 Error (this is a bug, should return 404), one way to avoid that is to specify a default value:
-- import: fastn/processors as pr

-- string message: hello     
$processor$: pr.request-data

-- ds.markdown: $message
Lang:
ftd
In this case we have provided a default value of hello, so if message is not found the HTTP request, the variable message be assigned the default value, hello.

Reading Multiple Bits In One Go

You can use a record to read multiple data from request.
curl 'http://127.0.0.1:8000/test/?message=hello%20world&flag=true'
Lang:
sh
In above example url contains query parameter message with value hello world and flag with value true. We can access them ftd file by using request-data processor.
-- import: fastn/processors as pr

-- record r-data:
string message: default value of message
boolean flag:

-- r-data data:
$processor$: pr.request-data

-- ds.markdown: $data.message
Lang:
ftd
Please note that all the parameters defined in the record must be present, or they must have a default value.

Key Values In Dynamic URLs And Sitemap

When using dynamic URLs or the sitemap, the key value parameters can also be extracted using the same method:
-- fastn.dynamic-urls:

# RD Test:
  url: /rd-test/<string:message>/
  document: ftd-host/r.ftd
  flag: false
Lang:
ftd
Here we have specified flag: false in the dynamic URL configuration, and it will be picked up.

JSON Body

If the request body is not empty, and has content type application/json, the body is parsed as JSON and the fields in your record are looked in the JSON as well.

Note On Priority

If a field is present in more than one places, this is the order of preference:
  • data in FASTN.ftd is highest priority
  • then comes data in JSON body
  • then the data in the named parameter
  • and finally the GET query parameter is lowest priority