@https_fn.on_request(cors=options.CorsOptions(cors_origins="*",cors_methods=["get","post"]))defdate(req:https_fn.Request)-> https_fn.Response:"""Get the server's local date and time."""
const{onRequest}=require('firebase-functions/v2/https');constexpress=require('express');constapp=express();// Add middleware to authenticate requestsapp.use(myMiddleware);// build multiple CRUD interfaces:app.get('/:id',(req,res)=>res.send(Widgets.getById(req.params.id)));app.post('/',(req,res)=>res.send(Widgets.create()));app.put('/:id',(req,res)=>res.send(Widgets.update(req.params.id,req.body)));app.delete('/:id',(req,res)=>res.send(Widgets.delete(req.params.id)));app.get('/',(req,res)=>res.send(Widgets.list()));// Expose Express API as a single Cloud Function:exports.widgets=onRequest(app);
Python
fromfirebase_adminimportinitialize_app,dbfromfirebase_functionsimporthttps_fnimportflaskinitialize_app()app=flask.Flask(__name__)# Build multiple CRUD interfaces:@app.get("/widgets")@app.get("/widgets/<id>")defget_widget(id=None):ifidisnotNone:returndb.reference(f"/widgets/{id}").get()else:returndb.reference("/widgets").get()@app.post("/widgets")defadd_widget():new_widget=flask.request.get_data(as_text=True)db.reference("/widgets").push(new_widget)returnflask.Response(status=201,response="Added widget")# Expose Flask app as a single Cloud Function:@https_fn.on_request()defhttpsflaskexample(req:https_fn.Request)-> https_fn.Response:withapp.request_context(req.environ):returnapp.full_dispatch_request()
[[["わかりやすい","easyToUnderstand","thumb-up"],["問題の解決に役立った","solvedMyProblem","thumb-up"],["その他","otherUp","thumb-up"]],[["必要な情報がない","missingTheInformationINeed","thumb-down"],["複雑すぎる / 手順が多すぎる","tooComplicatedTooManySteps","thumb-down"],["最新ではない","outOfDate","thumb-down"],["翻訳に関する問題","translationIssue","thumb-down"],["サンプル / コードに問題がある","samplesCodeIssue","thumb-down"],["その他","otherDown","thumb-down"]],["最終更新日 2025-09-05 UTC。"],[],[],null,["\u003cbr /\u003e\n\nYou can trigger a function through an HTTP request with a request\nhandler. This allows you to invoke a function through\nthe following supported HTTP methods: `GET`, `POST`, `PUT`, `DELETE`, and\n`OPTIONS`.\n\nAdditional HTTP options\n\n| Option | Description |\n|---------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `region` | HTTP functions may specify an array of regions as well as a single region. When multiple regions are specified, a separate function instance will be deployed for each region. |\n| `timeoutSeconds` (`timeout_sec` for Python) | HTTP functions may specify a timeout of up to one hour. |\n| `cors` | HTTP functions may specify CORS policies. You can set this to `true` to allow all origins or a `string`, `regex`, or `array` to specify allowed origins. Defaults to false/no CORS policies if not explicitly set. |\n\nConfiguring CORS (Cross-Origin Resource Sharing)\n\nUse the `cors` option to control which origins can\naccess your function. By default, HTTP functions don't have CORS configured,\nmeaning that any cross-origin request to your function results in this error: \n\n request has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.\n\nYou can also explicitly disable CORS by setting the `cors` option to `false`\nfor your function.\n\nTo allow some cross-origin requests, but not all, you can pass a list of\nspecific domains or regular expressions that should be allowed. For example, if\nyou own the domains `firebase.com` and `flutter.com`, and `firebase.com` can\nhave many subdomains, you might want to set the `cors` option to\n`[/firebase\\.com$/, 'https://flutter.com']` for Node.js or\n`[r'firebase\\.com$', r'https://flutter\\.com']` for Python: \n\nNode.js \n\n const { onRequest } = require(\"firebase-functions/v2/https\");\n\n exports.sayHello = onRequest(\n { cors: [/firebase\\.com$/, \"https://flutter.com\"] },\n (req, res) =\u003e {\n res.status(200).send(\"Hello world!\");\n }\n );\n\nPython \n\n from firebase_functions import https_fn, options\n\n @https_fn.on_request(\n cors=options.CorsOptions(\n cors_origins=[r\"firebase\\.com$\", r\"https://flutter\\.com\"],\n cors_methods=[\"get\", \"post\"],\n )\n )\n def say_hello(req: https_fn.Request) -\u003e https_fn.Response:\n return https_fn.Response(\"Hello world!\")\n\nIf your function should be openly available, for example if it's serving a\npublic API or website, set the `cors` policy to `true`.\n\nTrigger a function with an HTTP request\n\nUse the request handler for your platform ([`onRequest()`](/docs/reference/functions/2nd-gen/node/firebase-functions.https#httpsonrequest)\nor [`on_request`](/docs/reference/functions/python/firebase_functions.https_fn#on_request))\nto create a function that handles HTTP events. Examples in this section are based on a\n\"time server\" sample that triggers when you send\nan HTTP `GET` request to the functions endpoint. The sample function\nretrieves the current server time, formats the time as specified in a URL query\nparameter, and sends the result in the HTTP response.\n\nUsing request and response objects\n\nThe request object gives\nyou access to the properties of the HTTP request sent by the client, and the\nresponse object gives you a way to send a response back to the client. \n\nNode.js \n\n```javascript\nexports.date = onRequest(\n {timeoutSeconds: 1200, region: [\"us-west1\", \"us-east1\"]},\n (req, res) =\u003e {\n// ...\n});\n```\n\nPython \n\n @https_fn.on_request(cors=options.CorsOptions(cors_origins=\"*\", cors_methods=[\"get\", \"post\"]))\n def date(req: https_fn.Request) -\u003e https_fn.Response:\n \"\"\"Get the server's local date and time.\"\"\" \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Python/quickstarts/https-time-server/functions/main.py#L41-L45\n\n| **Important:** Make sure that all HTTP functions terminate properly. By terminating functions correctly, you can avoid excessive charges from functions that run for too long.\n\nUsing existing Express or Flask apps\n\nUsing the app as the argument for\nthe request handler, you can pass a full app to an HTTP function: \n\nNode.js \n\n const { onRequest } = require('firebase-functions/v2/https');\n\n const express = require('express');\n const app = express();\n\n // Add middleware to authenticate requests\n app.use(myMiddleware);\n\n // build multiple CRUD interfaces:\n app.get('/:id', (req, res) =\u003e res.send(Widgets.getById(req.params.id)));\n app.post('/', (req, res) =\u003e res.send(Widgets.create()));\n app.put('/:id', (req, res) =\u003e res.send(Widgets.update(req.params.id, req.body)));\n app.delete('/:id', (req, res) =\u003e res.send(Widgets.delete(req.params.id)));\n app.get('/', (req, res) =\u003e res.send(Widgets.list()));\n\n // Expose Express API as a single Cloud Function:\n exports.widgets = onRequest(app);\n\nPython \n\n from firebase_admin import initialize_app, db\n from firebase_functions import https_fn\n import flask\n\n initialize_app()\n app = flask.Flask(__name__)\n\n # Build multiple CRUD interfaces:\n\n\n @app.get(\"/widgets\")\n @app.get(\"/widgets/\u003cid\u003e\")\n def get_widget(id=None):\n if id is not None:\n return db.reference(f\"/widgets/{id}\").get()\n else:\n return db.reference(\"/widgets\").get()\n\n\n @app.post(\"/widgets\")\n def add_widget():\n new_widget = flask.request.get_data(as_text=True)\n db.reference(\"/widgets\").push(new_widget)\n return flask.Response(status=201, response=\"Added widget\")\n\n\n # Expose Flask app as a single Cloud Function:\n\n\n @https_fn.on_request()\n def httpsflaskexample(req: https_fn.Request) -\u003e https_fn.Response:\n with app.request_context(req.environ):\n return app.full_dispatch_request() \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Python/http-flask/functions/main.py#L16-L48\n\nInvoke an HTTP function\n\nAfter you deploy an HTTP function, you can invoke it through its own unique\nURL. Use the exact URL output from the CLI after deployment.\n\nFor example, the URL to invoke `date()` looks like this: \n\n https://us-central1-\u003cproject-id\u003e.cloudfunctions.net/date\n\nWith Express and Flask app routing, the function name is added as a prefix to\nthe URL paths in the app you define.\n\nRead values from the request\n\nIn the `date()` function example, the function tests both the URL parameter and\nthe body for a `format` value to set the date/time format to use: \n\nNode.js \n\n```javascript\nlet format = req.query.format;\nformat = req.body.format;https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node/quickstarts/https-time-server/functions/index.js#L68-L68\n```\n\nPython \n\n format = req.args[\"format\"] if \"format\" in req.args else None \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Python/quickstarts/https-time-server/functions/main.py#L55-L55\n\nTerminate HTTP Functions\n\nAfter retrieving and formatting the server time, the `date()` function\nconcludes by sending the result in the HTTP response: \n\nNode.js\n\nAlways end an HTTP function with `send()`, `redirect()`,\nor `end()`. Otherwise, your function might continue to run and be\nforcibly terminated by the system. See also\n[Sync, Async and Promises](/docs/functions/terminate-functions). \n\n```javascript\nconst formattedDate = moment().format(`${format}`);\nlogger.log(\"Sending formatted date:\", formattedDate);\nres.status(200).send(formattedDate);https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Node/quickstarts/https-time-server/functions/index.js#L73-L75\n```\n\nPython \n\n formatted_date = datetime.now().strftime(format)\n print(f\"Sending Formatted date: {formatted_date}\")\n return https_fn.Response(formatted_date) \n https://github.com/firebase/functions-samples/blob/c4fde45b65fab584715e786ce3264a6932d996ec/Python/quickstarts/https-time-server/functions/main.py#L67-L69\n\nIntegrating with Firebase Hosting\n\nYou can connect an HTTP function to Firebase Hosting. Requests on your\nFirebase Hosting site can be proxied to specific HTTP functions. This also\nallows you to use your own custom domain with an HTTP function. Learn more about\n[connecting Cloud Functions to Firebase Hosting](/docs/hosting/functions)."]]