REST APIs
Call a REST API from a function with fetch, using the GET, DELETE, POST, PUT, and PATCH methods with JSON data.
Make outbound HTTP requests from a function using the fetch API, covering the GET, DELETE, POST, PUT, and PATCH methods with JSON data. Use these snippets when your function needs to call a REST API, whether to read data, submit a form, or update a resource, while running close to the user on Azion’s global network.
Examples
Get
This function reads the list of items from the API and returns it to the client as JSON:
Delete
This function deletes the item 42 and returns the status the API answers with:
Post
This function creates an item from a JSON body and returns the response of the API:
Put
This function replaces the item 42 with a new JSON body:
Patch
This function changes only the price field of the item 42:
How it works
Each example is a complete function in the ES Modules pattern. The fetch handler calls fetch() with the URL of the API and an options object: method selects the HTTP verb, headers carries the Content-Type and the authorization token, and body carries the JSON string that JSON.stringify() produces. The token comes from the API_TOKEN environment variable through Azion.env.get(), so it stays out of the code. await fetch() resolves to a Response. The GET example reads it with response.json(), and the other examples return the status and body of the API to the client. Replace https://api.example.com/items and the sample values with the ones of your API.