Let's Run Jinyeah

[FastAPI] Build APIs 본문

Programming/Web

[FastAPI] Build APIs

jinyeah 2021. 11. 19. 19:36

FastAPI

Preparation

  • install fastapi and uvicorn(server that can run FastAPI applications) with pip
$ python -m pip install fastapi
$ python -m pip install uvicorn[standard]
  • save the code in a file called app.py
  • Run 
$ uvicorn app:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
  • open up browser and go to the url --> 자동으로 get 실행?

Example

# app.py
from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()

# to determine the id for the new country
def _find_next_id():
    return max(country.country_id for country in countries) + 1

class Country(BaseModel):
    country_id: int = Field(default_factory=_find_next_id, alias="id")
    name: str
    capital: str
    area: int

countries = [
    Country(id=1, name="Thailand", capital="Bangkok", area=513120),
    Country(id=2, name="Australia", capital="Canberra", area=7617930),
    Country(id=3, name="Egypt", capital="Cairo", area=1010408),
]

@app.get("/countries")
async def get_countries():
    return countries

@app.post("/countries", status_code=201)
async def add_country(country: Country):
    countries.append(country)
    return country

Get 

  • use decorator to connect GET requests to a function get_countries
  • when client access /countries, server calls the decorated function to hand the HTTP request and return a response
@app.get("/countries")
async def get_countries():
    return countries

Request with command-line

curl - allows you to send HTTP requests from the command line

  • -X sets the HTTP method for the request.
  • -H adds an HTTP header to the request.
  • -d defines the request data.
$ curl -i http://127.0.0.1:8000/countries -w '\n'

Response

[
    {
        "id": 1,
        "name":"Thailand",
        "capital":"Bangkok",
        "area":513120
    },
    {
        "id": 2,
        "name":"Australia",
        "capital":"Canberra",
        "area":7617930
    },
    {
        "id": 3,
        "name":"Egypt",
        "capital":"Cairo",
        "area":1010408
    }
]

Post

Request

$ curl -i http://127.0.0.1:8000/countries \
-X POST \
-H 'Content-Type: application/json' \
-d '{"name":"Germany", "capital": "Berlin", "area": 357022}' \
-w '\n'


HTTP/1.1 201 Created
content-type: application/json
...

{"id":4,"name":"Germany","capital":"Berlin","area": 357022}

 

 

참고

https://realpython.com/api-integration-in-python/#rest-architecture

'Programming > Web' 카테고리의 다른 글

[Python] Consuming APIs  (0) 2021.11.19
Build REST APIs  (0) 2021.11.19
REST API  (0) 2021.11.19
[Error]CSS style 변경 후 웹브라우저에 반영이 안되는 경우  (0) 2021.01.15
웹 서버란?  (0) 2021.01.07
Comments