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

# Make a get request to get the latest position of the international space station from the opennotify api.
response = requests.get("http://api.open-notify.org/iss-now.json")
# Print the status code of the response.
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

# Create some test data for our catalog in the form of a list of dictionaries.
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():
    # Check if an ID was provided as part of the URL.
    # If ID is provided, assign it to a variable.
    # If no ID is provided, display an error in the browser.
    if 'id' in request.args:
        id = int(request.args['id'])
    else:
        return "Error: No id field provided. Please specify an id."

    # Create an empty list for our results
    results = []

    # Loop through the data and match results that fit the requested ID.
    # IDs are unique, but other fields might return many results
    for book in books:
        if book['id'] == id:
            results.append(book)

    # Use the jsonify function from Flask to convert our list of
    # Python dictionaries to the JSON format.
    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# serverless.yml
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+}'