create rest api in python code example
Example 1: api in python
import requests
import json
r = requests.get("URL")
j=r.json()
print(j)
Example 2: python api tutorial
response = requests.get("http://api.open-notify.org/iss-now.json")
print(response.status_code)
Example 3: create a python api
import flask
from flask import request, jsonify
app = flask.Flask(__name__)
app.config["DEBUG"] = True
books = [
{'id': 0,
'title': 'A Fire Upon the Deep',
'author': 'Vernor Vinge',
'first_sentence': 'The coldsleep itself was dreamless.',
'year_published': '1992'},
{'id': 1,
'title': 'The Ones Who Walk Away From Omelas',
'author': 'Ursula K. Le Guin',
'first_sentence': 'With a clamor of bells that set the swallows soaring, the Festival of Summer came to the city Omelas, bright-towered by the sea.',
'published': '1973'},
{'id': 2,
'title': 'Dhalgren',
'author': 'Samuel R. Delany',
'first_sentence': 'to wound the autumnal city.',
'published': '1975'}
]
@app.route('/', methods=['GET'])
def home():
return '''<h1>Distant Reading Archive</h1>
<p>A prototype API for distant reading of science fiction novels.</p>'''
@app.route('/api/v1/resources/books/all', methods=['GET'])
def api_all():
return jsonify(books)
@app.route('/api/v1/resources/books', methods=['GET'])
def api_id():
if 'id' in request.args:
id = int(request.args['id'])
else:
return "Error: No id field provided. Please specify an id."
results = []
for book in books:
if book['id'] == id:
results.append(book)
return jsonify(results)
app.run()
Example 4: creating rest api in serverless with python
1$ sls deploy
2... snip ...
3Service Information
4service: serverless-flask
5stage: dev
6region: us-east-1
7stack: serverless-flask-dev
8api keys:
9 None
10endpoints:
11 ANY - https://bl4r0gjjv5.execute-api.us-east-1.amazonaws.com/dev
12 ANY - https://bl4r0gjjv5.execute-api.us-east-1.amazonaws.com/dev/{proxy+}
13functions:
14 app: serverless-flask-dev-app
Example 5: creating rest api in serverless with python
1
2
3service: serverless-flask
4
5plugins:
6 - serverless-python-requirements
7 - serverless-wsgi
8
9custom:
10 wsgi:
11 app: app.app
12 packRequirements: false
13 pythonRequirements:
14 dockerizePip: non-linux
15
16provider:
17 name: aws
18 runtime: python3.6
19 stage: dev
20 region: us-east-1
21
22functions:
23 app:
24 handler: wsgi.handler
25 events:
26 - http: ANY /
27 - http: 'ANY {proxy+}'