Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Cette page décrit comment structurer et annoter votre code Cloud Endpoints Frameworks. Pour obtenir la liste complète de toutes les annotations compatibles, consultez la page Annotations.
Cet exemple de squelette Endpoints Frameworks est disponible sous :
cdappengine-java8/endpoints-v2-skeleton/
Dans ce document qui vous explique le fonctionnement des annotations, nous utilisons l'exemple endpoints-v2-backend pour afficher les annotations et tout autre code que vous devez ajouter à l'exemple endpoints-v2-skeleton afin qu'il soit généré. Au final, l'exemple endpoints-v2-skeleton modifié se comporte de la même manière que l'exemple endpoints-v2-backend, qui est utilisé sur la page Premiers pas avec Endpoints Frameworks sur App Engine.
Créer et annoter le code
Pour annoter votre code, procédez comme suit :
Remplacez les répertoires actuels par le répertoire source Java du projet, par exemple : src/main/java/com/example/skeleton.
Créez un fichier de classe JavaBean nommé Message.java contenant le code suivant :
L'attribut version = "v1" spécifie la version de l'exemple d'API. La valeur que vous saisissez est incorporée dans le chemin spécifié dans l'URL de votre API. Pour en savoir plus sur les versions, consultez la page Gérer les versions d'une API.
Ajoutez la méthode echo suivante comme premier point de terminaison de l'API ainsi que la méthode d'assistance doEcho au fichier MyApi.java.
Copiez toutes les importations à partir de Echo.java, puis collez-les dans MyApi.java.
Maven
Créez le projet :
mvncleanpackage
Gradle
Créez le projet :
gradlecleanbuild
Principes de base des annotations
Trois types d'annotations sont couramment utilisées dans les API backend :
L'annotation @Api contient les détails de configuration de l'API backend.
L'annotation @ApiMethod marque une méthode de classe associée à l'API backend. Les méthodes qui ne sont pas marquées avec @ApiMethod ne sont pas incluses lorsque vous générez des bibliothèques clientes et des documents de découverte. L'annotation @ApiMethod peut également être utilisée afin de remplacer la configuration de l'API pour une méthode spécifique.
L'annotation @Named doit être ajoutée à tous les paramètres transmis aux méthodes côté serveur, sauf si le paramètre est un type d'entité.
Pour obtenir la liste complète de toutes les annotations Endpoints Frameworks, consultez la page Annotations et syntaxe.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/04 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/09/04 (UTC)."],[[["\u003cp\u003eThis page guides you through structuring and annotating Cloud Endpoints Frameworks code, utilizing the \u003ccode\u003eendpoints-v2-skeleton\u003c/code\u003e sample project.\u003c/p\u003e\n"],["\u003cp\u003eThe document explains how to use annotations like \u003ccode\u003e@Api\u003c/code\u003e, \u003ccode\u003e@ApiMethod\u003c/code\u003e, and \u003ccode\u003e@Named\u003c/code\u003e to define and configure your backend API.\u003c/p\u003e\n"],["\u003cp\u003eYou'll learn how to modify the \u003ccode\u003eMyApi.java\u003c/code\u003e file by defining API versions and adding an \u003ccode\u003eecho\u003c/code\u003e method as your first API endpoint.\u003c/p\u003e\n"],["\u003cp\u003eThe document uses the \u003ccode\u003eendpoints-v2-backend\u003c/code\u003e sample as a reference, so the end result of modifying the \u003ccode\u003eendpoints-v2-skeleton\u003c/code\u003e will behave identically.\u003c/p\u003e\n"],["\u003cp\u003eBuilding the project will require you to use Maven or Gradle, depending on which system you use.\u003c/p\u003e\n"]]],[],null,["# Writing and annotating the code\n\nThis page describes how to structure and annotate your\nCloud Endpoints Frameworks code. For a complete list of all supported\nannotations, see\n[Annotations](/endpoints/docs/frameworks/java/annotations).\n\nBefore you begin\n----------------\n\n1. [Set up your development environment](/endpoints/docs/frameworks/java/set-up-environment).\n2. Clone the skeleton Endpoints Frameworks example:\n\n git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git\n\n3. The skeleton Endpoints Frameworks example is located in:\n\n cd appengine-java8/endpoints-v2-skeleton/\n\nTo help explain how annotations work, this document uses the\n`endpoints-v2-backend` sample to show the annotations and other code that you\nmust add to the `endpoints-v2-skeleton` sample to get it to build. In the end,\nthe modified `endpoints-v2-skeleton` sample behaves the same as the\n`endpoints-v2-backend` sample, which is used in\n[Getting started with Endpoints Frameworks on App Engine](/endpoints/docs/frameworks/java/get-started-frameworks-java).\n\nCreating and annotating code\n----------------------------\n\nTo annotate your code:\n\n1. Change directories to the project's Java source directory, for example: `src/main/java/com/example/skeleton`.\n2. Create a [JavaBean](https://wikipedia.org/wiki/JavaBeans) class file named `Message.java` that contains the following code: \n\n public class Message {\n\n private String message;\n\n public String getMessage() {\n return this.message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n }\n\n3. Edit the `MyApi.java` file contained in the skeleton example. Change the `@Api` definition annotation with the following: \n\n @Api(\n name = \"echo\",\n version = \"v1\",\n namespace =\n @ApiNamespace(\n ownerDomain = \"echo.example.com\",\n ownerName = \"echo.example.com\",\n packagePath = \"\"\n ),\n // ...\n )\n\n The `version = \"v1\"` attribute specifies the version of the sample\n API. The value that you enter becomes part of the path in the URL to your\n API. For more information on versions, see\n [Handling API versioning](/endpoints/docs/frameworks/java/handling-api-versioning).\n4. Add the following `echo` method as your first API endpoint and the `doEcho` helper method to your `MyApi.java`. \n\n @ApiMethod(name = \"echo\")\n public Message echo(Message message, @Named(\"n\") @Nullable Integer n) {\n return doEcho(message, n);\n }\n\n private Message doEcho(Message request, Integer n) {\n Message response = new Message();\n if (n != null && n \u003e= 0) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i \u003c n; i++) {\n if (i \u003e 0) {\n sb.append(' ');\n }\n sb.append(request.getMessage());\n }\n response.setMessage(sb.toString());\n }\n return response;\n }\n\n5. Copy all of the imports from [`Echo.java`](https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/appengine-java8/endpoints-v2-backend/src/main/java/com/example/echo/Echo.java), and paste them in your `MyApi.java`.\n6.\n\n ### Maven\n\n Build the project: \n\n ```bash\n mvn clean package\n ```\n\n ### Gradle\n\n Build the project: \n\n ```bash\n gradle clean build\n ```\n\nAnnotation basics\n-----------------\n\nThere are three annotations commonly used in backend APIs:\n\n- [`@Api`](/endpoints/docs/frameworks/java/annotations#api_api-scoped_annotations) contains the configuration details of the backend API.\n- [`@ApiMethod`](/endpoints/docs/frameworks/java/annotations#apimethod_method-scoped_annotations) marks a class method that is part of the backend API. Methods that aren't marked with`@ApiMethod` aren't included when you generate client libraries and discovery docs. The `@ApiMethod` annotation can also be used to override the API configuration for a specific method.\n- [`@Named`](/endpoints/docs/frameworks/java/annotations#named) must be added to all parameters passed to server-side methods, unless the parameter is an entity type.\n\nFor a complete list of all Endpoints Frameworks annotations, see\n[Annotations and syntax](/endpoints/docs/frameworks/java/annotations).\n\nWhat's next\n-----------\n\n- [Learn about adding API management](/endpoints/docs/frameworks/java/adding-api-management).\n- [Learn about the supported parameter and return types](/endpoints/docs/frameworks/java/parameter-and-return-types).\n- [Learn about exceptions and status codes](/endpoints/docs/frameworks/java/exceptions)."]]