Exercise - Make functions RESTful
The Products Manager API is about to get serious style upgrade courtesy of you, the Tailwind Traders developer. In this exercise, you'll turn all of the functions you created earlier into RESTful ones by modifying their configuration files.
Make the GetProducts route RESTful
In Visual Studio Code, open the
api/src/index.ts
file.In the route definition for GetProducts, restrict the
methods
property so that it only contains the valueGET
.methods: ['GET']
Add the
route
property with a value ofproducts
for a full route of/api/products
.route: 'products',
The full route definition is:
app.http('GetProducts', { methods: ['GET'], route: 'products', // <- route: /api/products authLevel: 'anonymous', handler: GetProducts });
Save the file.
Note
Saving the file will cause the Azure Functions process to terminate the debugger, and it will disconnect. Don't be alarmed. You didn't break anything. It's just that you've made fundamental changes to how the functions are served up, so you'll have to restart the project when you're done with all this REST spring cleaning.
Make the CreateProduct function RESTful
Still in the
api/src/index.ts
file, restrict the allowedmethods
property toPOST
.methods: ['POST']
Add the
route
property with a value ofproducts
for a full route of/api/products
.route: 'products',
The full route definition is:
app.http('CreateProduct',{ methods: ['POST'], route: 'products', authLevel: 'anonymous', handler: CreateProduct });
Save the file.
Make the UpdateProduct function RESTful
Still in the
api/src/index.ts
file, restrict the allowedmethods
property toPUT
.methods: ['PUT'],
Add the
route
property with a value ofproducts
for a full route of/api/products
.route: 'products',
The full route definition is:
app.http('UpdateProduct', { methods: ['PUT'], route: 'products', authLevel: 'anonymous', handler: UpdateProduct });
Save the file.
Make the DeleteProduct function RESTful
Still in the
api/src/index.ts
file, restrict the allowedmethods
property toDELETE
.methods: ['DELETE']
Update the route to use the product id as a route parameter.
route: 'products/{id}',
The full route definition is:
app.http('DeleteProduct', { methods: ['DELETE'], route: 'products/{id}', authLevel: 'anonymous', handler: DeleteProduct });
Save the file.
Start the project
Start the Azure Functions project by pressing F5.
Notice that the URLs for your function endpoints are now different.
Look at that stunning API. It's simply gorgeous. Notice how you specified the same exact same route for the CreateProduct, UpdateProduct, and DeleteProduct functions. Only the HTTP request method is different. You've turned three URLs into one, while still having three endpoints. You're a magician.