This lesson will walk through using functions as a REST backend.
-
Create a
netlify.toml
file in your project.The
netlify.toml
file is where we configure how the site builds and where your serverless functions live. -
In
netlify.toml
, add a[build]
section and addpublish = "site"
andfunctions = "functions"
values -
We need to create this site in Netlify
Open your terminal and run the following command:
netlify init --manual
Choose "create & configure a new site", then add a site name or hit enter for one to be generated for you.
-
Create your API function
Create a function name
api
in the/functions
folder -
In
functions/api.js
, we are going to setup our API routerUse the
event.path
&event.httpMethod
to determine how to handle the request -
Create your API function
Create a function name
api
in the/functions
folder"See code"
exports.handler = async (event, context) => { const path = event.path.replace(/\.netlify\/functions\/[^/]+/, '') const segments = path.split('/').filter(e => e) switch (event.httpMethod) { case 'GET': // GET /.netlify/functions/api if (segments.length === 0) { return api.readAll(event, context) } // GET /.netlify/functions/api/123456 if (segments.length === 1) { event.id = segments[0] return api.read(event, context) } else { return { statusCode: 500, body: 'too many segments in GET request' } } // POST /.netlify/functions/api case 'POST': return api.create(event, context) // PUT /.netlify/functions/api/123456 case 'PUT': if (segments.length === 1) { event.id = segments[0] return api.update(event, context) } else { return { statusCode: 500, body: 'invalid segments in POST request, must be /.netlify/functions/api/123456' } } // DELETE /.netlify/functions/api/123456 case 'DELETE': if (segments.length === 1) { event.id = segments[0] return api.delete(event, context) } else { return { statusCode: 500, body: 'invalid segments in DELETE request, must be /.netlify/functions/api/123456' } } // Fallthrough case default: return { statusCode: 500, body: 'unrecognized HTTP Method, must be one of GET/POST/PUT/DELETE' } } }
-
Create a
/functions/methods
folderWe will add in our logic to handling the different routes here
-
Install the function dependencies
Change directories into your functions folder and install the dependencies
cd functions && npm install
This will install the
fauandb
sdk our functions will use to talk to our database.Install the faunaDB addon
netlify addons:create fauna
Scaffold our database schema
npm run setup
-
Deploy the site
Open your terminal and run the following command:
netlify deploy -p
Visit the frontend to verify your api works!
If you need help or get stuck refer to the completed code of this lesson