DeveloperBreeze

Python Code Snippet: Simple RESTful API with FastAPI

from fastapi import FastAPI
from pydantic import BaseModel
from typing import List

app = FastAPI()

class Book(BaseModel):
    title: str
    author: str

# Sample data
books_db = [
    Book(title="The Catcher in the Rye", author="J.D. Salinger"),
    Book(title="To Kill a Mockingbird", author="Harper Lee"),
    Book(title="1984", author="George Orwell")
]

@app.get("/books/", response_model=List[Book])
async def get_books():
    return books_db

@app.post("/books/", response_model=Book)
async def add_book(book: Book):
    books_db.append(book)
    return book

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)

Related Posts

More content you might like

Tutorial
javascript python

How to Build a Fullstack App with Flask and React

import React, { useState } from 'react';
import axios from 'axios';

function TaskForm({ onTaskCreated }) {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    axios.post('http://127.0.0.1:5000/tasks', { title, description, done: false })
      .then(response => {
        onTaskCreated(response.data);
        setTitle('');
        setDescription('');
      })
      .catch(error => console.log(error));
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>Title</label>
        <input type="text" value={title} onChange={e => setTitle(e.target.value)} />
      </div>
      <div>
        <label>Description</label>
        <input type="text" value={description} onChange={e => setDescription(e.target.value)} />
      </div>
      <button type="submit">Add Task</button>
    </form>
  );
}

export default TaskForm;

Now, update the main App.js file to handle new task creation:

Sep 30, 2024
Read More
Tutorial
javascript

التعامل مع JSON في JavaScript: قراءة البيانات وكتابتها

عند إرسال بيانات من الواجهة الأمامية إلى الخادم، يتم عادة تحويل البيانات إلى تنسيق JSON.

التعامل مع JSON هو جزء أساسي من تطوير تطبيقات الويب الحديثة. سواء كنت تحتاج إلى جلب البيانات من API أو كتابة بيانات إلى خادم، فإن فهم كيفية قراءة وكتابة JSON سيساعدك في بناء تطبيقات قوية وقابلة للتوسيع.

Sep 26, 2024
Read More
Tutorial
javascript

AJAX with JavaScript: A Practical Guide

AJAX (Asynchronous JavaScript and XML) allows web applications to update content asynchronously by exchanging data with a server behind the scenes. This means parts of your web page can be updated without requiring a full page reload, providing a smoother, more dynamic user experience.

In this guide, we'll explore how AJAX works, the basics of making AJAX requests using vanilla JavaScript, and some real-world examples to help you implement AJAX in your own projects.

Sep 18, 2024
Read More
Tutorial
python

Getting Started with Pydantic: Data Validation and Type Coercion in Python

Pydantic allows you to define constraints on fields, such as minimum and maximum values:

from pydantic import conint

class User(BaseModel):
    id: int
    name: str
    age: conint(ge=0, le=120)  # Age must be between 0 and 120

Aug 29, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Be the first to share your thoughts!