Organízate con las colecciones
Guarda y clasifica el contenido según tus preferencias.
Debes definir un servidor web que use la API o las APIs que hayas creado.
Cloud Endpoints Frameworks para Python implementa la interfaz estándar Web Server Gateway Interface (WSGI) para enrutar las solicitudes a tu API hacia los métodos de tu código.
Al igual que con cualquier aplicación que se ejecute en App Engine, debes crear un archivo llamado app.yaml en el que configures los ajustes de tu aplicación de App Engine. Para definir el servidor web, debes hacer cambios en el archivo app.yaml.
Para definir un servidor web, sigue estos pasos:
Crea un módulo de Python, por ejemplo main.py, y crea un objeto endpoints.api_server en el nivel superior:
api=endpoints.api_server([EchoApi])
El código api = endpoints.api_server([EchoApi]) crea una aplicación WSGI que dirige las solicitudes de la API a los métodos de la clase EchoAPI.
Puedes proporcionar una lista de objetos remote.Service (que definiste al crear tu API) a endpoints.api_server. Si tienes una API implementada en varias clases, tu objeto remote.Service es una colección de clases, tal como se describe en Crear una API implementada con varias clases.
Si creas un módulo independiente para el objeto endpoints.api_server, dependerá de si has creado una o varias APIs.
Si has creado varias APIs (con varias subclases remote.Service) que se definen en varios archivos, te recomendamos que crees un módulo independiente para el objeto endpoints.api_server para poder importar todos los archivos de clase.
Si has creado una sola API, puedes añadir el código endpoints.api_server necesario al módulo en el que definas tu API, ya que no tienes que importar ninguna otra clase.
En el archivo app.yaml, asigna el servidor web que acabas de crear a la ubicación de Cloud Endpoints de la siguiente manera:
handlers:# The endpoints handler must be mapped to /_ah/api.-url:/_ah/api/.*script:main.api
donde main es el módulo de Python en el que has definido el objeto endpoints.api_server.
Servir tu API desde una ruta diferente
Opcional: Para servir tu API desde otra ruta, por ejemplo, /api/, haz lo siguiente:
Endpoints Frameworks para Python usa el módulo de registro estándar de Python para registrar información sobre el estado de la aplicación y el ciclo de vida de las solicitudes. Para obtener más información sobre los registros de App Engine y cómo verlos, consulta el artículo Leer y escribir registros de aplicaciones de la documentación de App Engine.
El módulo de registro de Python proporciona niveles de registro predefinidos. Los niveles de registro, ordenados de menor a mayor gravedad, son los siguientes:
Nivel de registro
Descripción
DEBUG
Proporciona registros detallados. Normalmente, solo se define este nivel cuando se está solucionando un problema.
INFO
Nivel de registro predeterminado de Endpoints Frameworks. Te permite hacer un seguimiento del progreso de la aplicación a un nivel general.
WARNING
Te avisa de que ha ocurrido algo inesperado, pero la aplicación puede recuperarse y seguir funcionando con normalidad.
ERROR
Te avisa de que se ha producido un error que puede provocar la pérdida de algunas funciones, pero la aplicación sigue ejecutándose.
CRITICAL
Te avisa de que se ha producido un error o un evento grave que puede provocar que la aplicación se cierre.
Los registradores se organizan en una jerarquía separada por puntos. Por ejemplo, el registrador
endpoints.api_config es un elemento secundario del registrador endpoints. Esta jerarquía te permite controlar con precisión qué registros se emiten o se suprimen. Normalmente, solo se cambian los dos registradores raíz de Endpoints Frameworks: endpoints y endpoints_management.
Habilitar el registro de DEBUG para Endpoints Frameworks
Para evitar sobrecargar el lector de registros, Endpoints Frameworks configura sus registradores para que solo registren entradas de registro con el nivel de registro INFO o superior. En cualquier momento después de importar Endpoints Frameworks en tu módulo, puedes cambiar el nivel de registro de la siguiente manera:
[[["Es fácil de entender","easyToUnderstand","thumb-up"],["Me ofreció una solución al problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Es difícil de entender","hardToUnderstand","thumb-down"],["La información o el código de muestra no son correctos","incorrectInformationOrSampleCode","thumb-down"],["Me faltan las muestras o la información que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-11 (UTC)."],[[["\u003cp\u003eA web server must be defined within the \u003ccode\u003eapp.yaml\u003c/code\u003e file to route requests to your API's methods using the Web Server Gateway Interface (WSGI).\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eendpoints.api_server\u003c/code\u003e object, created in a Python module like \u003ccode\u003emain.py\u003c/code\u003e, functions as a WSGI application that routes API requests, with the option to include multiple \u003ccode\u003eremote.Service\u003c/code\u003e objects if you have a multi-class API.\u003c/p\u003e\n"],["\u003cp\u003eIn the \u003ccode\u003eapp.yaml\u003c/code\u003e file, you must map the web server to the Cloud Endpoints location, by setting the url handler to \u003ccode\u003e/_ah/api/.*\u003c/code\u003e or a different path if configured, and link the script to the module where \u003ccode\u003eendpoints.api_server\u003c/code\u003e was defined.\u003c/p\u003e\n"],["\u003cp\u003eEndpoints Frameworks for Python employs the standard Python logging module, with levels ranging from \u003ccode\u003eDEBUG\u003c/code\u003e to \u003ccode\u003eCRITICAL\u003c/code\u003e, defaulting to \u003ccode\u003eINFO\u003c/code\u003e, and can be modified using the \u003ccode\u003esetLevel\u003c/code\u003e method for loggers like \u003ccode\u003eendpoints\u003c/code\u003e and \u003ccode\u003eendpoints_management\u003c/code\u003e.\u003c/p\u003e\n"]]],[],null,["# Creating a web server\n\nYou must define a web server that uses the\n[API or APIs you have created](/endpoints/docs/frameworks/python/create_api).\nCloud Endpoints Frameworks for Python implements the standard\n[Web Server Gateway Interface](https://wsgi.readthedocs.io/)\n(WSGI) to route requests to your API to the methods in your code.\n\nAs with every application that runs on App Engine, you must create a file\ncalled [`app.yaml`](/appengine/docs/standard/python/config/appref) in which you\nconfigure your App Engine app's settings. To define the web server,\nyou make changes to your `app.yaml` file.\n\nTo define a web server:\n\n1. Create a Python module, for example `main.py`, and create an\n `endpoints.api_server` object at the top-level:\n\n api = endpoints.api_server([EchoApi])\n\n The code `api = endpoints.api_server([EchoApi])` creates a WSGI application\n that routes API requests to the methods in the `EchoAPI` class.\n\n You can provide a list of `remote.Service` objects (which you defined when\n you [created your API](/endpoints/docs/frameworks/python/create_api)) to\n `endpoints.api_server`. If you have an API that is implemented in several\n classes, then your `remote.Service` object is a collection of classes as\n described in [Creating an API implemented with multiple\n classes](/endpoints/docs/frameworks/python/create-multi-class-api).\n\n Whether you create a separate module for the `endpoints.api_server` object\n depends on whether you created a single API or multiple APIs.\n - If you created multiple APIs (using multiple `remote.Service`\n subclasses) that are defined in multiple files, then we recommend that\n you create a separate module for the `endpoints.api_server` object so\n that you can import all the class files.\n\n - If you created a single API, you can add the required\n `endpoints.api_server` code to the module where you define your API\n because you don't need to import any other classes.\n\n | **Warning:** if your code doesn't call `endpoints.api_server`, you will get a deployment failure when you try to deploy.\n2. In your `app.yaml` file, map the web server you just created to\n the Cloud Endpoints location as follows:\n\n handlers:\n # The endpoints handler must be mapped to /_ah/api.\n - url: /_ah/api/.*\n script: main.api\n\n where `main` is the Python module you in which you defined the\n `endpoints.api_server` object.\n\nServing your API from a different path\n--------------------------------------\n\nOptional: To serve your API from a different path, for example `/api/`:\n\n1. Modify the decorator:\n\n @endpoints.api(name='echo', version='v1', base_path='/api/')\n\n2. Change the `handlers` section in the `app.yaml` file:\n\n handlers:\n - url: /api/.*\n script: main.api\n\nLogging in Endpoints Frameworks for Python\n------------------------------------------\n\nEndpoints Frameworks for Python uses the\n[standard Python logging module](https://docs.python.org/2/library/logging.html)\nto log information about\nthe application's status and request lifecycle. To learn more about\nApp Engine logs and how to view them, review\n[Reading and writing application logs](/appengine/docs/standard/python/logs#writing_application_logs)\nin the App Engine documentation.\n\nThe Python logging module provides predefined log levels. In increasing order\nof severity, the log levels are:\n\nLoggers exist in a dot-separated hierarchy. For example, the logger\n`endpoints.api_config` is a child of the logger `endpoints`. This hierarchy\ngives you precise control over which logs are emitted or suppressed. Typically,\nyou only change the two root loggers for Endpoints Frameworks:\n`endpoints` and `endpoints_management`.\n\n### Enable `DEBUG` logging for Endpoints Frameworks\n\nTo avoid overloading the log reader, Endpoints Frameworks sets its\nloggers to only record log entries with the `INFO` log level or higher. At any\ntime after Endpoints Frameworks has been imported into your module,\nyou can change the log level as follows: \n\n import logging\n logging.getLogger('endpoints').setLevel(logging.DEBUG)\n logging.getLogger('endpoints_management').setLevel(logging.DEBUG)\n\nThe `setLevel` method sets the minimum log level for the logger."]]