View a markdown version of this page

Tutorial: Erstellen Sie eine REST-API mit AWS SDKs oder AWS CLI - Amazon API Gateway

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

Tutorial: Erstellen Sie eine REST-API mit AWS SDKs oder AWS CLI

Verwenden Sie das folgende Tutorial, um eine PetStore API zu erstellen, die die GET /pets/{petId} Methoden GET /pets und unterstützt. Die Methoden sind mit einem HTTP-Endpunkt integriert. Sie können diesem Tutorial mit dem AWS SDK für JavaScript, dem SDK for Python (Boto3) oder dem folgen. AWS CLI Das API richten Sie mithilfe der folgenden Funktionen und Befehle ein:

JavaScript v3
Python
AWS CLI

Weitere Informationen zum AWS SDK für JavaScript v3 finden Sie unter Wofür ist das AWS SDK? JavaScript . Weitere Informationen zum SDK für Python (Boto3) finden Sie unter AWS SDK für Python (Boto3). Weitere Informationen zu dem AWS CLI finden Sie unter Was ist der AWS CLI? .

Richten Sie eine Edge-optimierte API PetStore ein

In diesem Tutorial verwenden Beispielbefehle Platzhalterwerte für Werte IDs wie API-ID und Ressourcen-ID. Nach Abschluss des Tutorials ersetzen Sie die Beispielwerte mit Ihren eigenen Werten.

Um eine PetStore Edge-optimierte API einzurichten, verwenden Sie AWS SDKs
  1. Erstellen Sie mithilfe des folgenden Beispiels eine RestApi-Entity:

    JavaScript v3
    import {APIGatewayClient, CreateRestApiCommand} from "@aws-sdk/client-api-gateway"; (async function (){ const apig = new APIGatewayClient({region:"us-east-1"}); const command = new CreateRestApiCommand({ name: "Simple PetStore (JavaScript v3 SDK)", description: "Demo API created using the AWS SDK for JavaScript v3", version: "0.00.001", binaryMediaTypes: [ '*'] }); try { const results = await apig.send(command) console.log(results) } catch (err) { console.error(Couldn't create API:\n", err) } })();

    Ein erfolgreicher Aufruf gibt Ihre API-ID und die Root-Ressourcen-ID Ihrer API in einer Ausgabe wie folgt zurück:

    { id: 'abc1234', name: 'PetStore (JavaScript v3 SDK)', description: 'Demo API created using the AWS SDK for node.js', createdDate: 2017-09-05T19:32:35.000Z, version: '0.00.001', rootResourceId: 'efg567' binaryMediaTypes: [ '*' ] }
    Python
    import botocore import boto3 import logging logger = logging.getLogger() apig = boto3.client('apigateway') try: result = apig.create_rest_api( name='Simple PetStore (Python SDK)', description='Demo API created using the AWS SDK for Python', version='0.00.001', binaryMediaTypes=[ '*' ] ) except botocore.exceptions.ClientError as error: logger.exception("Couldn't create REST API %s.", error) raise attribute=["id","name","description","createdDate","version","binaryMediaTypes","apiKeySource","endpointConfiguration","disableExecuteApiEndpoint","rootResourceId"] filtered_result ={key:result[key] for key in attribute} print(filtered_result)

    Ein erfolgreicher Aufruf gibt Ihre API-ID und die Root-Ressourcen-ID Ihrer API in einer Ausgabe wie folgt zurück:

    {'id': 'abc1234', 'name': 'Simple PetStore (Python SDK)', 'description': 'Demo API created using the AWS SDK for Python', 'createdDate': datetime.datetime(2024, 4, 3, 14, 31, 39, tzinfo=tzlocal()), 'version': '0.00.001', 'binaryMediaTypes': ['*'], 'apiKeySource': 'HEADER', 'endpointConfiguration': {'types': ['EDGE']}, 'disableExecuteApiEndpoint': False, 'rootResourceId': 'efg567'}
    AWS CLI
    aws apigateway create-rest-api --name 'Simple PetStore (AWS CLI)' --region us-west-2

    Die Ausgabe dieses Befehls ist wie folgt:

    { "id": "abcd1234", "name": "Simple PetStore (AWS CLI)", "createdDate": "2022-12-15T08:07:04-08:00", "apiKeySource": "HEADER", "endpointConfiguration": { "types": [ "EDGE" ] }, "disableExecuteApiEndpoint": false, "rootResourceId": "efg567" }

    Die von Ihnen erstellte API hat die API-ID abcd1234 und die Root-Ressourcen-ID efg567. Diese Werte verwenden Sie nun bei der Einrichtung Ihrer API.

  2. Als Nächstes erstellen Sie eine untergeordnete Ressource für die Root-Ressource. Hierzu geben Sie RootResourceId als den parentId-Eigenschaftswert an. Erstellen Sie anhand des folgenden Beispiels eine /pets-Ressource für Ihre API:

    JavaScript v3
    import {APIGatewayClient, CreateResourceCommand } from "@aws-sdk/client-api-gateway"; (async function (){ const apig = new APIGatewayClient({region:"us-east-1"}); const command = new CreateResourceCommand({ restApiId: 'abcd1234', parentId: 'efg567', pathPart: 'pets' }); try { const results = await apig.send(command) console.log(results) } catch (err) { console.log("The '/pets' resource setup failed:\n", err) } })();

    Ein erfolgreicher Aufruf gibt Informationen zur Ressource in einer Ausgabe wie folgt zurück:

    { "path": "/pets", "pathPart": "pets", "id": "aaa111", "parentId": "efg567'" }
    Python
    import botocore import boto3 import logging logger = logging.getLogger() apig = boto3.client('apigateway') try: result = apig.create_resource( restApiId='abcd1234', parentId='efg567', pathPart='pets' ) except botocore.exceptions.ClientError as error: logger.exception("The '/pets' resource setup failed: %s.", error) raise attribute=["id","parentId", "pathPart", "path",] filtered_result ={key:result[key] for key in attribute} print(filtered_result)

    Ein erfolgreicher Aufruf gibt Informationen zur Ressource in einer Ausgabe wie folgt zurück:

    {'id': 'aaa111', 'parentId': 'efg567', 'pathPart': 'pets', 'path': '/pets'}
    AWS CLI
    aws apigateway create-resource --rest-api-id abcd1234 \ --region us-west-2 \ --parent-id efg567 \ --path-part pets

    Die Ausgabe dieses Befehls ist wie folgt:

    { "id": "aaa111", "parentId": "efg567", "pathPart": "pets", "path": "/pets" }

    Die von Ihnen erstellte /pets-Ressource hat die Ressourcen-ID aaa111. Diesen Wert verwenden Sie bei der Einrichtung Ihrer API.

  3. Als Nächstes fügen Sie der /pets-Ressource eine untergeordnete Ressource hinzu. Diese Ressource, /{petId}, besitzt einen Pfadparameter für die {petId}. Wenn Sie einen Teil eines Pfads zu einem Pfadparameter machen wollen, setzen Sie ihn in geschweifte Klammern { }. Erstellen Sie anhand des folgenden Beispiels eine /pets/{petId}-Ressource für Ihre API:

    JavaScript v3
    import {APIGatewayClient, CreateResourceCommand } from "@aws-sdk/client-api-gateway"; (async function (){ const apig = new APIGatewayClient({region:"us-east-1"}); const command = new CreateResourceCommand({ restApiId: 'abcd1234', parentId: 'aaa111', pathPart: '{petId}' }); try { const results = await apig.send(command) console.log(results) } catch (err) { console.log("The '/pets/{petId}' resource setup failed:\n", err) } })();

    Ein erfolgreicher Aufruf gibt Informationen zur Ressource in einer Ausgabe wie folgt zurück:

    { "path": "/pets/{petId}", "pathPart": "{petId}", "id": "bbb222", "parentId": "aaa111'" }
    Python
    import botocore import boto3 import logging logger = logging.getLogger() apig = boto3.client('apigateway') try: result = apig.create_resource( restApiId='abcd1234', parentId='aaa111', pathPart='{petId}' ) except botocore.exceptions.ClientError as error: logger.exception("The '/pets/{petId}' resource setup failed: %s.", error) raise attribute=["id","parentId", "pathPart", "path",] filtered_result ={key:result[key] for key in attribute} print(filtered_result)

    Ein erfolgreicher Aufruf gibt Informationen zur Ressource in einer Ausgabe wie folgt zurück:

    {'id': 'bbb222', 'parentId': 'aaa111', 'pathPart': '{petId}', 'path': '/pets/{petId}'}
    AWS CLI
    aws apigateway create-resource --rest-api-id abcd1234 \ --region us-west-2 \ --parent-id aaa111 \ --path-part '{petId}'

    Die Ausgabe dieses Befehls ist wie folgt:

    { "id": "bbb222", "parentId": "aaa111", "path": "/pets/{petId}", "pathPart": "{petId}" }

    Die von Ihnen erstellte /pets/{petId}-Ressource hat die Ressourcen-ID bbb222. Diesen Wert verwenden Sie bei der Einrichtung Ihrer API.

  4. In den nächsten zwei Schritten fügen Sie HTTP-Methoden zu Ihren Ressourcen hinzu. In diesem Tutorial legen Sie fest, dass die Methoden offenen Zugriff haben sollen. Hierfür setzen Sie authorization-type auf NONE. Damit nur authentifizierte Benutzer die Methode aufrufen können, können Sie IAM-Rollen und -Richtlinien, einen Lambda-Genehmiger (früher als benutzerdefinierter Genehmiger bekannt) oder einen Amazon Cognito-Benutzerpool verwenden. Weitere Informationen finden Sie unter Steuern und verwalten Sie den Zugriff auf REST APIs in API Gateway.

    Fügen Sie anhand des folgenden Beispiels die /pets-HTTP-Methode der GET-Ressource hinzu:

    JavaScript v3
    import {APIGatewayClient, PutMethodCommand } from "@aws-sdk/client-api-gateway"; (async function (){ const apig = new APIGatewayClient({region:"us-east-1"}); const command = new PutMethodCommand({ restApiId: 'abcd1234', resourceId: 'aaa111', httpMethod: 'GET', authorizationType: 'NONE' }); try { const results = await apig.send(command) console.log(results) } catch (err) { console.log("The 'GET /pets' method setup failed:\n", err) } })();

    Ein erfolgreicher Aufruf gibt Folgendes zurück:

    { "apiKeyRequired": false, "httpMethod": "GET", "authorizationType": "NONE" }
    Python
    import botocore import boto3 import logging logger = logging.getLogger() apig = boto3.client('apigateway') try: result = apig.put_method( restApiId='abcd1234', resourceId='aaa111', httpMethod='GET', authorizationType='NONE' ) except botocore.exceptions.ClientError as error: logger.exception("The 'GET /pets' method setup failed: %s", error) raise attribute=["httpMethod","authorizationType","apiKeyRequired"] filtered_result ={key:result[key] for key in attribute} print(filtered_result)

    Ein erfolgreicher Aufruf gibt Folgendes zurück:

    {'httpMethod': 'GET', 'authorizationType': 'NONE', 'apiKeyRequired': False}
    AWS CLI
    aws apigateway put-method --rest-api-id abcd1234 \ --resource-id aaa111 \ --http-method GET \ --authorization-type "NONE" \ --region us-west-2

    Die Ausgabe dieses Befehls ist wie folgt:

    { "httpMethod": "GET", "authorizationType": "NONE", "apiKeyRequired": false }
  5. Fügen Sie anhand des folgenden Beispiels die GET-HTTP-Methode zur /pets/{petId}-Ressource hinzu und legen Sie die requestParameters-Eigenschaft so fest, dass der vom Client bereitgestellte petId-Wert an das Backend übergeben wird: