I wanted to make an API test server with GCP Language: React, Flask
I thought I should draw it with an api from somewhere, but it's dull (** Learn Udon ** links to talk about udon wiki % E3% 81% 86% E3% 81% A9% E3% 82% 93)) Yelp API使ってこんな感じにした
Yelp api I used yelp api because everyone knows Japanese food sites and I think it's a good idea to take a look overseas.
Getting the api key is easy. If you enter yelp developers and register with your google or facebook account, it will be issued immediately.
Flask
Directory structure
app
├── config.py
└── run.py
# run.py
from flask import Flask, request
from flask_cors import CORS
import requests
import config
app = Flask(__name__)
CORS(app)
URL = "https://api.yelp.com/v3/businesses/search"
headers = {'Authorization': f"Bearer {config.API_KEY}"}
@app.route('/')
def ramen_yelp():
payload = {
"term": request.args.get("term", "ramen"),
"location": request.args.get("location", "ny")
}
response = requests.request("GET", URL, headers=headers, params=payload)
return response.json()
if __name__ == "__main__":
app.run(host="0.0.0.0", port=config.PORT, debug=config.DEBUG_MODE)
In the case of root ('/'), the ramen ranking in New York is set by default.
Flask, gunicorn settings in config Put the important thing in the env variable
# config.py
from os import environ
import multiprocessing
PORT = int(environ.get("PORT", 8080))
DEBUG_MODE = int(environ.get("DEBUG_MODE", 1))
API_KEY = environ.get("API_KEY")
bind = ":" + str(PORT)
workers = multiprocessing.cpu_count() * 2 + 1
threads = multiprocessing.cpu_count() * 2
If you enter ** 0.0.0.0:8080 ** from your browser (firefox or chrome)
I started to spit out the result with json
Convert flask to docker and upload to GCR
The Dockerfile looks like this
# pull official base image
FROM python:3.8.1-alpine
# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# install dependencies
RUN pip install --upgrade pip
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
# set work directory
WORKDIR /usr/src/app
# copy project
COPY ./app .
ENV PORT 80
ENV API_KEY YOUR_API_KEY
CMD ["gunicorn", "run:app", "--config=config.py"]
# requirements.txt
Flask==1.1.1
gunicorn==20.0.4
requests==2.23.0
Flask-Cors==3.0.8
** For production, use API_KEY dotenv to put it together in config.py *
Next, you can easily register by typing the command as follows
#!/bin/sh
docker build -t flask-test-gcr
docker tag flask-test-gcr [HOSTNAME]/[PROJECT-ID]/flask-test-gcr
docker push [HOSTNAME]/[PROJECT-ID]/flask-test-gcr
gcloud container images list-tags [HOSTNAME]/[PROJECT-ID]/flask-test-gcr
Like this
GCE(Google Compute Engine) Create an instance from the gcp console screen
The machine specs are a test, so let's make it the weakest!
If you want to deploy immediately from a container using docker, don't forget to check and container image below
If you set the external IP of the GCE VM instance screen to * http: [IP] *, you can get the same result! If you don't have an SSL certificate, you have to set the external IP to * http * instead of * https *.
Make a note of this IP address as it will be called from React
Easy with a nice boiler plate called create-react-app
# app-name is your favorite name
npx create-react-app app-name
App.js is mostly a template, with the difference between calling images, links, and Yelp.js Components.
// App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Yelp from './Yelp' //← This
function App() {
return (
<div className="main">
<Yelp />
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="Udon logo" />
<a
className="App-link"
href="https://ja.wikipedia.org/wiki/%E3%81%86%E3%81%A9%E3%82%93"
target="_blank"
rel="noopener noreferrer"
>
Learn Udon
</a>
</header>
</div>
</div>
);
}
export default App;
// Yelp.js
import React, { useEffect, useState } from 'react'
import './Yelp.css'
const Yelp = () => {
const [error, setError] = useState(null)
const [yelpData, setYelpData] = useState({})
useEffect(() => {
const API_URL = 'http://The external IP you noted earlier/'
fetch(API_URL)
.then(res => res.json())
.then(
result => {
setYelpData(result)
})
.catch(e => {
setError(e)
})
}, [])
if (error) {
return (
<div className="Yelp">error</div>
)
} else if (yelpData.businesses) {
const images = yelpData.businesses.map(item => {
return (
< a key={item.id} href={item.url} target="_blank" rel="noopener noreferrer" >
< img
height="150" width="150" crop="fill" radius="20"
src={item.image_url} alt="ramen"
/>
</a >
)
})
return (
<div className="Yelp">
{images}
</div>
)
} else {
return (
<div className="Yelp"></div>
)
}
}
export default Yelp
After that, if you start it locally, a ramen image will come out
#Start-up
yarn start
Click on your favorite image to jump to the Yelp link for more details
Run Docker images registered in Container Registry (GCR) on GCE
Recommended Posts