aws-python-rest-api-with-pymongo
Create the Mongo Atlas backend
- Follow
Part 1: Cluster Creation
of this artice to create a cluster on Mongo Atlas' Free Tier.
Deploy the Serverless API to AWS
-
Install Serverless
npm install -g serverless -
Install
serverless-python-requirements
npm i --save serverless-python-requirements -
Define necessary environment variables
Append this to your ~/.bash_profile
export MONGO_DB_USER=export MONGO_DB_PASS=export MONGO_DB_NAME=SampleDatabaseexport MONGO_COLLECTION_NAME=SampleCollectionexport MONGO_DB_URL= -
Deploy the API
sls deployYour results should look something like this:
Serverless: Stack update finished...Service Informationservice: serverless-pymongo-item-apistage: devregion: us-east-1stack: serverless-pymongo-item-api-devresources: 28api keys:Noneendpoints:POST - https://0xfyi15qci.execute-api.us-east-1.amazonaws.com/dev/itemGET - https://0xfyi15qci.execute-api.us-east-1.amazonaws.com/dev/itemGET - https://0xfyi15qci.execute-api.us-east-1.amazonaws.com/dev/item/{id}DELETE - https://0xfyi15qci.execute-api.us-east-1.amazonaws.com/dev/item/{id}functions:create: serverless-pymongo-item-api-dev-createlist: serverless-pymongo-item-api-dev-listget: serverless-pymongo-item-api-dev-getdelete: serverless-pymongo-item-api-dev-deletelayers:NoneServerless: Removing old service artifacts from S3...Serverless: Run the "serverless" command to setup monitoring, troubleshooting and testing.
Test the API by Creating and Querying items
Substitute your endpoints into these curl commands to test the Create, Read, and Delete operations
CREATE
curl --request POST \ --url https://0xfyi15qci.execute-api.us-east-1.amazonaws.com/dev/item \ --header 'content-type: application/json' \ --data '{ "attribute_1": "Pet", "attribute_2": "Rock"}'
Expected Response
204 status
{ "_id": "c6f03ca0-f792-11e9-9534-260a4b91bfe9", "data": { "attribute_1": "Pet", "attribute_2": "Rock" }}
GET
curl --request GET \ --url https://0xfyi15qci.execute-api.us-east-1.amazonaws.com/dev/item/c6f03ca0-f792-11e9-9534-260a4b91bfe9 \ --header 'content-type: application/json'
Expected Response
200 status
{ "_id": "c6f03ca0-f792-11e9-9534-260a4b91bfe9", "data": { "attribute_1": "Pet", "attribute_2": "Rock" }}
LIST
curl --request GET \ --url https://0xfyi15qci.execute-api.us-east-1.amazonaws.com/dev/item \ --header 'content-type: application/json'
Expected Response
200 status
{ "response_items": [ { "_id": "c6f03ca0-f792-11e9-9534-260a4b91bfe9", "data": { "attribute_1": "Pet", "attribute_2": "Rock" } }, { "_id": "717c5f36-f799-11e9-a921-1e0e685be73c", "data": { "attribute_1": "Pete", "attribute_2": "Rock" } } ], "filter": null}
Delete
curl --request DELETE \ --url https://0xfyi15qci.execute-api.us-east-1.amazonaws.com/dev/item/c6f03ca0-f792-11e9-9534-260a4b91bfe9 \ --header 'content-type: application/json'
Expected Response
204 status